0% found this document useful (0 votes)
28 views80 pages

1 Presentation1

Uploaded by

beastfoam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views80 pages

1 Presentation1

Uploaded by

beastfoam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

C# Programming and .

Net
Text Book:
C# Programming : From problem Analysis to program design, Barbara
Doyle, II edition, Cengage learning.
Programming Microsoft® Visual C#® 2008: The Language 2nd Edition –
Donis Marshall
References :
Pro C# with .NET 3.0, Andrew Troelsen, Special Edition, Dream tech
Press, India, 2007.
Inside C#, Tom Archer, WP Publishers, 2001.
The Complete Reference C#, Herbert Schildt, Tata McGraw Hill, 2004.
Programming in C++,E Balagurusamy, A Primer Second Edition,TMH
2009
• With the introduction of the .NET framework,
Microsoft included a new language called C#
(pronounced C Sharp).
• C# is designed to be a simple, modern,
general-purpose, object-oriented programming
language, borrowing key concepts from several
other languages, most notably Java.
• C# could theoretically be compiled to machine
code, but in real life, it's always used in combination
with the .NET framework.
• Therefore, applications written in C#, requires the
.NET framework to be installed on the computer
running the application.
• While the .NET framework makes it possible to
use a wide range of languages, C# is
sometimes referred to as THE .NET language,
perhaps because it was designed together
with the framework.
• C# is an Object Oriented language and does
not offer global variables or functions.
• Everything is wrapped in classes, even simple
types like int and string, which inherits from
the System.Object class.

• OOP is based on three key principles :
– Encapsulation (binds together code and data)
– Inheritance (mechanism where one class can
inherit the functionality of another
– Polymorphism (defines one interface that
describes a general set of actions)
Definitions
• An object is an instance of a class
• An object has identity, state and behaviour
• A C# program is basically a collection of
classes.
• A class is defined by a set of declaration
statements and methods containing
instructions known as executable statements.
Difference between Object and Class
• A class is a template for creating an object
• An object is an instance of a class
• An object has memory and reference
• C# can be written with any text editor, like
Windows Notepad, and then compiled with
the C# Command line compiler, csc.exe, which
comes with the .NET framework.
• However, most people prefer to use an IDE
(Integrated Development Environment), and
Microsoft offers several options for this.
• Their flagship is Visual Studio, which can be used
to work on every possible aspect of the .NET
framework.
• This product is very advanced, and comes in
several editions.
• Visual Studio is not exactly cheap, and might even
be too advanced for hobby programmers.
• With .NET framework 2.0, Microsoft introduced
the so-called Express versions, targeted at hobby
programmers and people wanting to try .NET, and
they continued this tradition with the later release
of .NET 3.0 and 3.5.
• For C# programming, you should download the
Visual C# Express from
http://www.microsoft.com/express/download/.
.NET Framework
• .NET represents an advanced new generation
of software that will drive the Next Generation
Internet
• It’s purpose is to make information available
any time, any place, and on any device
• .NET is a software framework that includes
everything required for developing software
for web services
• It integrates presentation technologies,
component technologies and data
technologies on a single platform so as to
enable users to develop internet applications
as easily as they do on desktop systems
• .NET platform provides a new environment for
creating and running robust, scalable and
distributed applications over the web
• .NET platform has three distinct technologies
– Common Language Runtime
– Framework base classes
– User and program Interfaces (ASP.NET and
Winforms)
Characteristics of C#
• Simple – C# simplifies C++ by eliminating
operations such as ->, :: and pointers
• Consistent- C# supports unified type system
• Modern- modern approach to debugging
• Object-oriented – supports encapsulation,
Inheritance and polymorphism
Applications of C#
• Console application
• Windows application
• Developing windows controls
• Developing ASP.NET projects
• Creating web controls
• Providing web services
• Developing .NET component library
A Demonstration of Visual C# 2008,
• If you have ever learnt a programming
language, you know that they all start with the
"Hello, world!" example, and who are we to
break such a fine tradition?
• Start Visual C# Express,
• select File -> New project…
• From the project dialog, select the Console
application.
• Once you click Ok, Visual C# Express creates a
new project for you, including a file called
Program.cs.
using System;
class Hello
{
static void Main()
{
Console.WriteLine(“Hello, World”);
}
}
• C# is a case-sensitive language
• Like Java, C# inherits its basic syntax from C
and C++
– Syntactic punctuation (such as ;, {})
– features (such as case sensitivity)
– keywords (such as void, class, public)
Compiling and Running the application
• The default file extension for C# programs is .cs
– Eg., hello.cs
• Try running the application by pushing F5 on your
keyboard.
• Or it can be compiled with the command line
directive
– csc hello.cs
• This will produce an executable program named
hello.exe
Escape sequences
• Special backslash character constants that are
used in output methods
• \a - alert
• \b - back space
• \f - form feed
• \n - new line
• \r- carriage return
• \t- horizontal tab
• \v - vertical tab
• \”- single quote
• \”” - double quote
• \\- back slash
• \0 - null
The code of your first application
1. using System;
2. namespace Prg2
3. {
4. class Program
5. {
6. static void Main()
7. { Console.WriteLine("Hello, world!");
8. Console.ReadLine();
9. }
10. }
11. }
• Once again, hit F5 to run it, and you will see
the black window actually staying, and even
displaying our greeting to the world.
• The first line tells the compiler that this program uses types from the
System namespace
• Line 2 declares a new namespace, called Prg2
– The new namespace starts at the open curly brace on line 3 and extends through
the matching curly brace on line 11
– Any types declared within this section are members of the namespace
• Line 4 declares a new class type called Program
– Any members declared between the matching curly braces on line 5 and 10 are
members that make up this class.
• Line 6 declares a method called Main as a member of class Program
– Main is a special function used by the compiler as the starting point of the
program
• Line 8 constitutes the body of Main
– Simple Statement are terminated by semi-colon.
– The first statement uses the Console class in namespace System to output a line
of text, and the second one reads a line of text from the console.
Hello world explained

• Let's start with the shortest and most common


characters in our code: The { and }.
• They are often referred to as curly braces, and in
C#, they mark the beginning and end of a logical
block of code.
• The curly braces are used in lots of other
languages, including C++, Java, JavaScript and
many others.
• As you can see in the code, they are used to wrap
several lines of code which belongs together.
Now let's start from the beginning
using System;
using System.Collections.Generic;
using System.Text;
• using is a keyword, highlighted with blue by the editor.
• The using keyword imports a namespace, and a namespace
is a collection of classes.
• Classes bring us some sort of functionality, and when
working with an advanced IDE like Visual C# Express, it will
usually create parts of the trivial code for us.
• In this case, it created a class for us, and imported the
namespaces which is required or expected to be used
commonly.
• In this case, 3 namespaces are imported for us, each
containing lots of useful classes.
• For instance, we use the Console class, which is a part of the
System namespace.
As you can see, we even get our own
namespace:
• namespace ConsoleApplication1
• The namespace ConsoleApplication1 is now
the main namespace for this application, and
new classes will be a part of it by default.
• Obviously, you can change this, and create
classes in another namespace.
• In that case, you will have to import this new
namespace to use it in your application, with
the using statement, like any other
namespace.
• Next, we define our class.
• Since C# is truly an Object Oriented language,
every line of code that actually does
something, is wrapped inside a class.
• In the case, the class is simply called Program:

class Program
• We can have more classes, even in the same file.
• For now, we only need one class.
• A class can contain several variables, properties
and methods, concepts we will go deeper into
later on.
• For now, all you need to know is that our current
class only contains one method and nothing else.
• It's declared like this:

static void Main(string[] args)


• This line is probably the most complicated one
in this example, so let's split it up a bit.
• The first word is static.
• The static keyword tells us that this method
should be accessible without instantiating the
class.
• The next keyword is void, and tells us what
this method should return.
• For instance, int could be an integer or a string
of text, but in this case, we don't want our
method to return anything, or void, which is
the same as no type.
• The next word is Main, which is simply the
name of our method.
• This method is the so-called entry-point of our
application, that is, the first piece of code to
be executed, and in our example, the only
piece to be executed.
• Now, after the name of a method, a set of
arguments can be specified within a set of
parentheses.
• In our example, our method takes only one
argument, called args.
• The type of the argument is a string, or to be
more precise, an array of strings.
Common elements in Visual C# 2008
Data types
• Data types are used everywhere in a programming language
like C#.
• Because it's a strongly typed language, you are required to
inform the compiler about which data types you wish to use
every time you declare a variable.
• bool is one of the simplest data types.
– It can contain only 2 values - false or true.
– The bool type is important to understand when
using logical operators like the if statement.
• int is short for integer, a data type for storing
numbers without decimals.
• When working with numbers, int is the most commonly
used data type.
• Integers have several data types within C#, depending on
the size of the number they are supposed to store.
• string is used for storing text, that is, a number of
chars.
• In C#, strings are immutable, which means that strings are
never changed after they have been created.
• When using methods which changes a string, the actual
string is not changed - a new string is returned instead.
• char is used for storing a single character.
• float is one of the data types used to store
numbers which may or may not contain
decimals.
Variables
• A variable can be compared to a storage room, and is
essential for the programmer.
• In C#, a variable as:
<data type> <name>;
An example could look like this:
string name;

• That's the most basic version.


• To assign a visibility to the variable, and perhaps assign a
value to it at the same time :
<visibility> <data type> <name> = <value>;
And with an example:
private string name = "John Doe";
Example
using System;
namespace ConsoleApplication1
{ class Program
{ static void Main(string[] args)
{ string firstName = "John";
string lastName = "Doe"; Console.WriteLine("Name: "
+ firstName + " " + lastName);
Console.WriteLine("Please enter a new first name:");
firstName = Console.ReadLine(); Console.WriteLine("New
name: " + firstName + " " + lastName);
Console.ReadLine(); } } }
• To enter a new first name
– use the ReadLine() method to read the user input
from the console and into the firstName variable.
– Once the user presses the Enter key, the new first
name is assigned to the variable, and in the next line
we output the name presentation again, to show the
change.
– We have just used our first variable and the single
most important feature of a variable: The ability to
change its value at runtime.
Math or computation

int number1, number2;


Console.WriteLine("Please enter a number:");
number1 = int.Parse(Console.ReadLine());
Console.WriteLine("Thank you. One more:");
number2 = int.Parse(Console.ReadLine());
Console.WriteLine("Adding the two numbers: " + (number1 +
number2));
Console.ReadLine();
• int.Parse() method is used to read a string and
convert it into an integer.
• The application makes no effort to validate the
user input, and if you enter something which
is not a number, an exception will be raised.
The if statement

• One of the single most important statements


in every programming language is the if
statement.
• Being able to set up conditional blocks of code
is a fundamental principal of writing software.
• The if statement needs a boolean result, that
is, true or false.
• Or compare variables to something, to
generate a true or false.
Example
using System;
namespace ConsoleApplication1
{ class Program
{ static void Main(string[] args)
{ int number;
Console.WriteLine("Please enter a number between 0 and 10:");
number = int.Parse(Console.ReadLine());
if(number > 10)
Console.WriteLine("Hey! The number should be 10 or less!");
else if(number < 0)
Console.WriteLine("Hey! The number should be 0 or more!");
else
Console.WriteLine("Good job!");
Console.ReadLine();
}
}
}
• As you may have noticed, we don't use the {
and } characters to define the conditional
blocks of code.
• The rule is that if a block only contains a
single line of code, the block characters are
not required.
Example
if((number > 10) || (number < 0))
Console.WriteLine("Hey! The number should be 0 or more and
10 or less!");
else
Console.WriteLine("Good job!");
• We put each condition in a set of parentheses,
and then we use the || operator, which simply
means "or", to check if the number is either
more than 10 OR less than 0.
• Another operator you will be using a lot is the
AND operator, which is written like this: &&.
Example
if((number <= 10) && (number >= 0))
Console.WriteLine("Good job!");
else
Console.WriteLine("Hey! The number should be 0 or more
and 10 or less!");
The switch statement

• The switch statement is like a set of if


statements.
• It's a list of possibilities, with an action for
each possibility, and an optional default
action, in case nothing else evaluates to true.
Example
int number = 1;
switch(number)
{
case 0: Console.WriteLine("The number is
zero!");
break;
case 1: Console.WriteLine("The number is one!");
break;
}
• The identifier to check is put after the switch
keyword, and then there's the list of case
statements, where we check the identifier
against a given value.
• Break statement at the end of each case. To
leave the block before it ends.
• In case of a function, you could use a return
statement instead of the break statement.
Example
Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Great!");
break;
case "no":
Console.WriteLine("Too bad!");
break;
}
Loops

• The ability to repeat a block of code X times.


• In C#, they come in 4 different variants, and
we will have a look at each one of them.
• The while loop
• Executes a block of code as long as the
condition given is true.
Example
using System;
namespace ConsoleApplication1
{ class Program
{ static void Main(string[] args)
{
int number = 0;
while(number < 5)
{
Console.WriteLine(number); number = number + 1;
}
Console.ReadLine();
}
}
}
• The do loop
• evaluates the condition after the loop has
executed, which makes sure that the code
block is always executed at least once.
do
{
Console.WriteLine(number);
number = number + 1;
} while(number < 5);

The output is the same though - once the


number is more than 5, the loop is exited.
• The for loop
• Used when the number of iterations is known.
Example
using System;
namespace ConsoleApplication1
{ class Program
{ static void Main(string[] args)
{ int number = 5;
for(int i = 0; i < number; i++)
Console.WriteLine(i);
Console.ReadLine();
}
}
}
• It consists of 3 parts - we initialize a variable
for counting, set up a conditional statement to
test it, and increment the counter (++ means
the same as "variable = variable + 1").
• The first part, where we define the i variable
and set it to 0, is only executed once, before
the loop starts. The last 2 parts are executed
for each iteration of the loop. Each time, i is
compared to our number variable - if i is
smaller than number, the loop runs one more
time. After that, i is increased by one.
• The foreach loop
• It operates on collections of items,
– Eg., arrays or other built-in list types.
Example
using System;
using System.Collections;
namespace ConsoleApplication1
{ class Program
{ static void Main(string[] args)
{ ArrayList list = new ArrayList();
list.Add("John Doe");
list.Add("Jane Doe");
list.Add("Someone Else");
foreach(string name in list)
Console.WriteLine(name);
Console.ReadLine();
}
}
}
• foreach loop is used to run through each item,
setting the name variable to the item we have
reached each time.
• Name a variable to output.
• In the eg. above, the name variable to be of the
string type is declared
– we always need to tell the foreach loop which datatype
you are expecting to pull out of the collection.
– For a list of various types, use the object class instead of
a specific class, to pull out each item as an object.
Functions

• A function allows to encapsulate a piece of


code and call it from other parts of the code.
• Used to repeat a piece of code, from multiple
places.
Example
<visibility> <return type>
<name>(<parameters>)
{ <function code> }
• To call a function,
– write its name,
– an open parenthesis,
– then parameters, if any,
– a closing parenthesis,
Example
public void DoStuff()
{
Console.WriteLine("I'm doing something...");
}
• The first part, public, is the visibility, and is
optional.
• If not defined, then the function will be
private.
• The type to return could be any valid type in
C#, or void.
• A void means that this function returns
absolutely nothing.
Example
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
Example
int result = AddNumbers(10, 5);
Console.WriteLine(result);
Function parameters

• In the previous chapter, we had a look at


functions. We briefly discussed parameters,
but only briefly. While parameters are very
simple and straight forward to use, there are
tricks which can make them a lot more
powerful.

You might also like