21 Eylül 2012 Cuma

CSHARP TUTORIAL ( C Sharp Tutorial)





C-Sharp


This csharp tutorial ( C sharp tutorial) is intended for beginners who want to learn C# programming ( C sharp) If you want to jump to coding, and you have the compiler for C sharp (C# ) installed in your computer, skip this introduction and go directly to next page of csharp tutorial . Otherwise go ahead and read on. 


INTRODUCTION


What is Csharp ( C# ) 

* The C# programming language (pronounced "C-Sharp") is a powerful object-oriented programming languages. 
* C# was developed by Microsoft. 
* It enables programmers to quickly build a wide range of applications for the .NET platform. 
* C# reduces the development time of applications and also to attain good productivity. 
* All .NET languages, including C#, follow the Common Language Specification (CLS). 

How to get started ( A quick start guide for those willing to take up Csharp tutorial) 

To get started, a compiler and an editor will be required. There are several options for obtaining a compiler to write C# programs. Microsoft Visual C# Express is a good compiler and editor tool to install. It is free. Go to http://www.microsoft.com/express/vcsharp/ and click on the download. Save the vcssetup.exe at your desired location. Click on the vccsetup.exe and install the Visual C Sharp at desire location. The setup process will take about half an hour. You will have to register the product otherwise it will expire in 30 days. 

Once you have done that, you are all set to start taking up this csharp tutorial . 


Your First Hello World Program



Start Visual C# Express. If you run the C# for the first time it will take slightly more time as it configures the environment for the first time. Once C# is running select File -> New project. From the project dialog, select the Console application. This is the most basic application type on a Windows system,. Once you click Ok, Visual C# Express creates a new project for you, including a file called Program.cs. It should look something like this:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}





Now write the following two line within the inner two braces

Console.WriteLine("Hello, world!");
Console.ReadLine();

The whole thing now should look as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 Console.WriteLine("Hello, world!");
 Console.ReadLine();
        }
    }
}


Hit F5 to run the above code. If you have not make any typographical mistake the program will actually run and display a black window displaying Hello World.

In the two lines that we wrote the first lin Writes a line in the console window. The second line reads a line in the window.

The second line is required because, without it the program will run and come out of it. So before you could observe the output on the console window, the program finishes the task and the console window is closed. Try running the code with only the first line and see what happens.

You have completed the installation of your first c# program. In the next chapter we will develop detailed C# concepts.

 





Explaining Hello World Program



Let us take a look at the first four lines of the code.


 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;





"using" is a keyword. A keyword is higlighted in blue in Microdoft IDE editor. The keyword using imports a namespace. A namespace is a collection of classes. We will get into the details of classes later on. For now you can assume the classes as a set of variables, properties and classes. In our program we have imported four namespaces. If you notice, we have our own namespace ConsoleApplication1.

 namespace ConsoleApplication1




Next we define our own class. The C# is an Object Oriented language. every line of code that actually does something, is wrapped inside a class. In the case, the class is called Program.

class Program





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)


We will now explain the above line. The first word static is a keyword. The static keyword tells us that this method should be accesible without creating an instance ofthe class. The next keyword is void, and tells us what this method should return. The void means it returns nothing. For instance, int could be an integer or a string of tex. The next word is Main, is 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. Windows applications can always be called with an optinal set of arguments. These arguments will be passed as text strings to our main method.


C# Variables



We will start this chapter wil the simple example below that takes in length and breadth of a rectangle and calculates and displays the area of the rectangle. Take a look at the following example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
     int length;
            int breadth;
            int area;

            length = 20;
            breadth = 10;

            area = length * breadth;

            Console.WriteLine("Area of Rectangle is : {0}", area);
            Console.ReadLine();


        }
    }
}


If you run the above program you should be able to see an output on the dos prompt type console window which shows the area of the rectangle. Take a look at the definition of the length, breadth and area variables.


 
     int length;
            int breadth;
            int area;

"Variables" are storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. In the above example length, breadth and area are variables. The variables can be of any one of the several possible types. In the above example these variables are of type "int" wich stands for integer.

C# has a number of types that includes boolean, integral ( int, uint, long, char, uchar,sbyte, byte etc), Floating Point Types ( float, double, decimal), string type etc.

C# Operators


Take a look at the following line in the above example

        length = 20;
        breadth = 10;

 area = length * breadth;

In C# Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. In the above example the first two statements assign values to variables length and breadth using "=" assignment operator. In the third line in the above example the variable area is assigned a value using = and * arithmetic operator.

This completes the basic tutorial of understanding the variables and operators. In the next chapter we will present a complete list of variables and operators for your reference.

Comments in C#



A comment is just a text that you can write to explain or describe your code. 

There are two ways we can write cmments in C# - Multi line comments and single line comments 

The multi-line comments begin with the characters "/*" and end with the characters "*/" as following: 

/* this code calculates the 
* area of a rectangle */ 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
     int length;
            int breadth;
            int area;

            length = 20;
            breadth = 10;



            area = length * breadth;

  /* this code calculates the 
   area of a rectangle */
  
     Console.WriteLine("Length of Rectangle is : {0}", length); 
     Console.WriteLine("Breadth of Rectangle is : {0}", breadth); 
            Console.WriteLine("Area of Rectangle is : {0}", area);
            Console.ReadLine();


        }
    }
}

If you run the above program you should be able to see an output something similar to 



 
Length of Rectangle is 20
Breadth of Rectangle is 10
Area of rectangle is 200



Commenting is often used as debugging aid. We can comment out a section of code to see what result it gives. For example take a look at the code ... 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
     int length;
            int breadth;
            int area;

            length = 20;
            breadth = 10;



            area = length * breadth;

  /* this code calculates the 
   area of a rectangle 
  
     Console.WriteLine("Length of Rectangle is : {0}", length); 
     Console.WriteLine("Breadth of Rectangle is : {0}", breadth); 

  */
            Console.WriteLine("Area of Rectangle is : {0}", area);
            Console.ReadLine();


        }
    }
}



We have commented out a section of code displaying the length and breadth of the rectangle. This gives the following output. 



Area of rectangle is 200



The single-line comments begin with the characters "//" and you can write your comments only at this line as the following: // This is a single line comment If you want to write more than one line in your comment then you must begin each line with "//" characters as following: // This code is very complex to undestand // Refer to documentation at www.referencedesigner.com for details 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
    int length;
           int breadth;
           int area;

           length = 20;
           breadth = 10;

           area = length * breadth;// Calculate the area of rectangle

            Console.WriteLine("Area of Rectangle is : {0}", area); 
            Console.ReadLine();

 // The program ends here. 
 // Now save it and hit F5 to run the program   


        }
    }
}


This completes your understanding of the comments in C#. In the next chapter we will show you how to display the values of variables and string using the Writeline command. These comment and Writeline form the two building blocks of C# that you will use to experiment various example codes of C# 


WriteLine formatting in C#



WriteLine is used to output a line of string in C#. It is often required to output a integer, string or other variable in a certain way. We need to use formatting in such cases. 
The format parameter in formatting is embedded with zero or more format specifications of the form "{ N [, M ][: formatString ]}", arg1, ... argN, where: 
* N is a zero-based integer indicating the argument to be formatted. 
* M is an optional integer indicating the width of the region to contain the formatted value, padded with spaces. If M is negative, the formatted value is left-justified; if M is positive, the value is right-justified. 
* formatString is an optional string of formatting codes. 
* argN is the expression to use at the equivalent position inside the quotes in the string. 
Consider the following example to understand it 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
 Console.WriteLine("{0,5} {1,5}", 123, 456);      // Right-aligned
 Console.WriteLine("{0,-5} {1,-5}", 123, 456);    // Left-aligned
 Console.WriteLine("{0,-10:D6} {1,-10:D6}", 123, 456); // D6 means 6 decimal digits
        Console.ReadLine();


        }
    }
}

If you run the above program you should be able to see an output something similar to 


 
  123  456
123  456
000123     000456



Format Specifiers


Standard numeric format strings are used to return strings in commonly used formats. They take the form X0, in which X is the format specifier and 0 is the precision specifier. The format specifier can be one of the nine built-in format characters that define the most commonly used numeric format types, as shown in Table 10-1. 
Table 10-1 - String and WriteLine Format Specifiers 
Character
Interpretation
C or c
Currency
D or d
Decimal (decimal integer�don�t confuse with the .NETDecimal type)
E or e
Exponent
F or f
Fixed point
G or g
General
N or n
Currency
P or p
Percentage
R or r
Round-trip (for floating-point values only); guarantees that a numeric value converted to a string will be parsed back into the same numeric value
X or x
Hex



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
        int i = 123456;
        Console.WriteLine("{0:C}", i); // $123,456.00
        Console.WriteLine("{0:D}", i); // 123456
        Console.WriteLine("{0:E}", i); // 1.234560E+005
        Console.WriteLine("{0:F}", i); // 123456.00
        Console.WriteLine("{0:G}", i); // 123456
        Console.WriteLine("{0:N}", i); // 123,456.00
        Console.WriteLine("{0:P}", i); // 12,345,600.00 %
        Console.WriteLine("{0:X}", i); // 1E240
        Console.ReadLine();


        }
    }
}



If you run above you should see the following command 


$123,456.00
123456
1.234560E+005
123456.00
123456
123,456.00
12,345,600.00 %
1E240


If the standard formatting specifiers aren�t enough for you, you can use picture format strings to create custom string output. Picture format definitions are described using placeholder strings that identify the minimum and maximum number of digits used, the placement or appearance of the negative sign, and the appearance of any other text within the number, as shown in Table 10-2.
Table 10-2 - Custom Format Specifiers 
Format Character
Purpose
Description
0
Display zero placeholder
Results in a nonsignificant zero if a number has fewer digits than there are zeros in the format
#
Display digit placeholder
Replaces the pound symbol (#) with only significant digits
.
Decimal point
Displays a period (.)
,
Group separator
Separates number groups, as in 1,000
%
Percent notation
Displays a percent sign (%)
E+0
E-0
e+0
e-0
Exponent notation
Formats the output of exponent notation
\
Literal character
Used with traditional formatting sequences such as �\n� (newline)
'ABC'
"ABC"
Literal string
Displays any string within quotes or apostrophes literally
;
Section separator
Specifies different output if the numeric value to be formatted is positive, negative, or zero
Let�s see the strings that result from a set of customized formats, using first a positive integer, then using the negative value of that same integer, and finally using zero:

The example below shows the results in comments based upon the format specifier. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
int i = 123456;
Console.WriteLine();
Console.WriteLine("{0:#0}", i);             // 123456

Console.WriteLine("{0:#0;(#0)}", i);        // 123456

Console.WriteLine("{0:#0;(#0);}", i); // 123456

        Console.WriteLine("{0:#%}", i);     // 12345600%


i = -123456;
Console.WriteLine();
Console.WriteLine("{0:#0}", i);             // -123456

Console.WriteLine("{0:#0;(#0)}", i);        // (123456)

Console.WriteLine("{0:#0;(#0);}", i); // (123456)

Console.WriteLine("{0:#%}", i);             // -12345600%


i = 0;
Console.WriteLine();
Console.WriteLine("{0:#0}", i);             // 0

Console.WriteLine("{0:#0;(#0)}", i);        // 0

Console.WriteLine("{0:#0;(#0);}", i); // 

Console.WriteLine("{0:#%}", i);             // %

Console.ReadLine();
        }
    }
}


This completes your understanding of formatting in C#. You like to experiment on your own to further strengthen your understanding of WriteLine formatting. We will use WriteLine formatting to understand some aspects of C# in next few chapters. 




C# Variables in detail



Let us explore more about the variable types in C Sharp.The table below lists the predefined value types. Because in C# all of the apparently fundamental value types are in fact built up from the object type. The list also indicates which System types in the .Net framework correspond to these pre-defined types.

C# Type.Net Framework (System) typeSigned?Bytes OccupiedPossible Values
sbyteSystem.SbyteYes1-128 to 127
shortSystem.Int16Yes2-32768 to 32767
intSystem.Int32Yes4-2147483648 to 2147483647
longSystem.Int64Yes8-9223372036854775808 to 9223372036854775807
byteSystem.ByteNo10 to 255
ushortSystem.Uint16No20 to 65535
uintSystem.UInt32No40 to 4294967295
ulongSystem.Uint64No80 to 18446744073709551615
floatSystem.SingleYes4Approximately +/- 1.5 x 10-45 to +/- 3.4 x 1038 with 7 significant figures
doubleSystem.DoubleYes8Approximately +/- 5.0 x 10-324 to +/- 1.7 x 10308 with 15 or 16 significant figures
decimalSystem.DecimalYes12Approximately +/- 1.0 x 10-28 to +/- 7.9 x 1028 with 28 or 29 significant figures
charSystem.CharN/A2Any Unicode character (16 bit)
boolSystem.BooleanN/A1 / 2true or false


Let us take a look at the following example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
     int length;
            int breadth;
            int area;

            length = 20;
            breadth = 10;

            area = length * breadth;

            Console.WriteLine("Area of Rectangle is : {0}", area);
            Console.ReadLine();


        }
    }
}


If you run the above program you should be able to see an output on the dos prompt type console window which shows the area of the rectangle. Take a look at the definition of the length, breadth and area variables.


 
     int length;
            int breadth;
            int area;

"Variables" are storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. In the above example length, breadth and area are variables. The variables can be of any one of the several possible types. In the above example these variables are of type "int" wich stands for integer.

C# has a number of types that includes boolean, integral ( int, uint, long, char, uchar,sbyte, byte etc), Floating Point Types ( float, double, decimal), string type etc.

C# Operators


Take a look at the following line in the above example

        length = 20;
        breadth = 10;

 area = length * breadth;

In C# Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. In the above example the first two statements assign values to variables length and breadth using "=" assignment operator. In the third line in the above example the variable area is assigned a value using = and * arithmetic operator.

This completes the basic tutorial of understanding the variables and operators. In the next chapter we will present a complete list of variables and operators for your reference.


C# Operators



Let us explore more about the operators types in C Sharp.T

Results in C# are computed by building expressions.  These expressions are built by combining variables and operators together into statements. . The following table describes the operators, their precedence, and associativity.
Table 2-4. Operators with their precedence and Associativity
Category (by precedence)Operator(s)Associativity
Primary(x)  x.y  f(x)  a[x]  x++  x--  new  typeof  sizeof  checked  uncheckedleft
Unary+  -  !  ~  ++x  --x  (T)xleft
Multiplicative*  /  %left
Additive+  -left
Shift<<  >>left
Relational<  >  <=  >=  isleft
Equality==  !=right
Logical AND&left
Logical XOR^left
Logical OR|left
Conditional AND&&left
Conditional OR||left
Ternary?:right
Assignment=  *=  /=  %=  +=  -=  <<=  >>=  &=  ^=  |=right
Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left.
Most operators are either unary or binary. Unary operators form expressions on a single variable, but binary operators form expressions with two variables. We will first try to understand the familiar binary operators. Take a look at the example below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
  int x, y, result;
        float floatresult;

        x = 7;
        y = 5;

        result = x+y;
        Console.WriteLine("x+y: {0}", result);

        result = x-y;
        Console.WriteLine("x-y: {0}", result);

        result = x*y;
        Console.WriteLine("x*y: {0}", result);

        result = x/y;
        Console.WriteLine("x/y: {0}", result);

        floatresult = (float)x/(float)y;
        Console.WriteLine("x/y: {0}", floatresult);

        result = x%y;
        Console.WriteLine("x%y: {0}", result);

        result += x;
        Console.WriteLine("result+=x: {0}", result);


 Console.ReadLine();
        }
    }
}


If you run the above code, you should see the output something similar to the below.

x+y: 12
x-y: 2
x*y: 35
x/y: 1
x/y: 1.4
x%y: 2
result+=x: 9



Let us now take a look at at the unitary operators.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
int x = 0;
            int preIncrement;
            int preDecrement;
            int postIncrement;
            int postDecrement;
            int positive;
            int negative;
            sbyte bitNot;
            bool logNot;

            preIncrement = ++x;
            Console.WriteLine("pre-Increment: {0}", preIncrement);

            preDecrement = --x;
            Console.WriteLine("pre-Decrement: {0}", preDecrement);

            postDecrement = x--;
            Console.WriteLine("Post-Decrement: {0}", postDecrement);

            postIncrement = x++;
            Console.WriteLine("Post-Increment: {0}", postIncrement);

            Console.WriteLine("Final Value of x: {0}", x);

            positive = -postIncrement;
            Console.WriteLine("Positive: {0}", positive);

            negative = +postIncrement;
            Console.WriteLine("Negative: {0}", negative);

            bitNot = 0;
            bitNot = (sbyte)(~bitNot);
            Console.WriteLine("Bitwise Not: {0}", bitNot);

            logNot = false;
            logNot = !logNot;
            Console.WriteLine("Logical Not: {0}", logNot);


Console.ReadLine();
        }
    }
}



If you run the above program you will see the output similar to the following

pre-Increment: 1
pre-Decrement: 0
Post-Decrement: 0
Post-Increment: -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: True





C# Pointers



A pointer is a variable that holds the memory address of another type. In C#, pointers can only be declared to hold the memory addresses of value types (except in the case of arrays).

Pointers are declared implicitly, using the symbol *, as in the following example:

int *p;

[Note that some coders place the dereferencer symbol immediately after the type name, eg.

int* p;

This variation appears to work just as well as the previous one.]

This declaration sets up a pointer 'p', which will point to the initial memory address of an integer (stored in four bytes).

The combined syntactical element *p ('p' prefixed by the dereferencer symbol '*') is used to refer to the type located at the memory location held by p. Hence given its declaration, *p can appear in integer assignments like the following:

*p = 5;

This code gives the value 5 to the integer that was initialised by the declaration. It is important, however, not to confuse such an assignment with one in which the derefencer symbol is absent, e.g.

p = 5;

The effect of this assignment is to change the memory location held by p. It doesn't change the value of the integer initialised by the original declaration; it just means that p no longer points to that integer. In fact, p will now point to the start of the four bytes present at memory location 5.

Another important symbol for using pointers is the operator &, which in this context returns the memory address of the variable it prefixes. To give an example of this symbol, the following code sets up p to point to integer i's memory location:

int i = 5;
int *p;
p = &i;

Given the above, the code

*p = 10;

changes the value of i to 10, since '*p' can be read as 'the integer located at the memory value held by p'.
Let us take a look at the following exmple that captures most of the concepts stated above

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 
  int x ;

            unsafe
            {
                int x = 100;

                /* The &x gives the memory address of the variable x,
                 * which we can assign to a pointer variable */

                int* ptr = &x;
                Console.WriteLine((int)ptr); // Displays the memory address
                Console.WriteLine(*ptr); // Displays the value at the memory 
                Console.ReadLine();
        }
    }
}


Before you will be able to run the above code you will have to change some settings. Go to Projects -> Properties ->Build and check the checkbox against "Allow unsafe code".

If you run the above code, you should see the output something similar to the below.

69725392
100








C# Loops



To consider the need of loops look at the following example which prints area of a square for values of its side increasing from 1 to 5.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 int x = 1;
  int area;
 area = x * x;
 Console.WriteLine("Area with side = 1 is {0}",area);
     x = 2;
     area = x * x;
     Console.WriteLine("Area with side = 2 is {0}", area);
     x = 3;
     area = x * x;
     Console.WriteLine("Area with side = 3 is {0}", area);
     x = 4;
     area = x * x;
     Console.WriteLine("Area with side = 4 is {0}", area);
     x = 5;
     area = x * x;
     Console.WriteLine("Area with side = 5 is {0}", area);

        Console.ReadLine();


        }
    }
}

If you run the above program you should be able to see an output something similar to


 
Area with side = 1 is 1
Area with side = 2 is 4
Area with side = 3 is 9
Area with side = 4 is 16
Area with side = 5 is 25


While it is perfectly ok to write the above program and get the desired result. However, it has inbuilt coding and storage inefficiency. Just assume if you need to repat the same thing for 100 values of x.
It is here that the loops in C# become useful. Look at the same program using a for loop in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
 int x = 1;
        int area;
        while (x <= 5)
        {
        area = x * x;
        Console.WriteLine("Area with side = {0} is {1}", x , area);
        x = x + 1;
        }

        Console.ReadLine();


        }
    }
}

The output of the above code is exactly the same as the previous code. You will notice that this keeps the code clean and introduces some "element" of programming.
We will now formally take a look at the while loop

While Loop



syntax:
while (expression)
{
statement[s]
}

A 'while' loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the boolean expression returns false.

For Loop


A for loop produces results similar to while loop. However that the syntax of the for loop includes initialization.
For loops are good for when you know exactly how many times you want to perform the statements within the loop.
The contents within the for loop parenthesis holds three sections separated by semicolons () { }. 
The initializer list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialize an integer to be used as a counter. 
Once the initializer list has been evaluated, the for loop gives control to its second section, the boolean expression. There is only one boolean expression, but it can be as complicated as you like as long as the result evaluates to true or false. The boolean expression is commonly used to verify the status of a counter variable. 
When the boolean expression evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the iterator list, which is normally used to increment or decrement a counter. The iterator list can contain a comma separated list of statements, but is generally only one statement. 
Probably the best way to understand a for loop is not the reading of above details but looking at the following code 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
  int x;
           int area;
           for (x = 1; x <= 5; x++ )
           {
            area = x * x;
            Console.WriteLine("Area with side = {0} is {1}", x, area);
                
           }

        Console.ReadLine();


        }
    }
}


When the for loop first starts the statement 
x =1; 
is executed. It then check the boolean expression 
x<=5; 
Since this is true, it enters the for loop. Inside the for loop it executes the two statements 
area = x * x; Console.WriteLine("Area with side = {0} is {1}", x, area); 
Next it again goes into the for loop and executes the third statement in the for loop 
x++ 
It increases the vale of x by 1. It then again evaluates the boolean expression x<=5 and continues ....
The program comes out of the for loop when the value of x becomes 6. 
There are also do while and for each loop. This will be updated later in this tutorial. 

This completes your understanding of loops in C#. Loops will continue to form major building block in all the practical programs you will be doing in your real life. 



C# Classes



We have already been using classes in C#. It is now time to learn classes in C# formally. In its most basic form a class in C# consists of some variables and some functions that are to be performed. The function in C# classes are called methods.

We would like to jump start and understand it with an example. Let us assume that we want to define a class called rectangle. The basic idea is that we want to have a variable of this class - it will be its length and breadth. The next thing is - we want to perform some actions on this class. Two possible actions are evaluating its area and perimeter.

Let us jump start and write and run following code in C# Express.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Rectangle
{
    int length, breadth;
    int area;    

    
    public void definerectangle(int length_input, int breadth_input)
    {
        length = length_input;
        breadth =  breadth_input;
    }

    
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            Rectangle rect1 = new Rectangle();
            rect1.definerectangle(10, 20);
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}

If you run the above program you should be able to see an output something similar to


 
Area of Rectangle is 200



The concept of this program is simple. We define a class Rectangle. There are two parts of this class. One is a list of the class variable. This class has three variables - length, breadth and area. Take a look at the following code that defines the variables of this class.

class Rectangle
{
    int length, breadth;
    int area;    

|




This part was easy to understant. There nothing very new to it. The thing that makes classes powerful is when we define the methods that can be perfdormed on these classes. Here we define two methods on this class - one is definerectangle and the other is calculatearea.


class Rectangle
{
    int length, breadth;
    int area;    

    
    public void definerectangle(int length_input, int breadth_input)
    {
        length = length_input;
        breadth =  breadth_input;
    }

    
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}





The method definerectangle() sets the length and breadth of the rectangle and the method calculatearea() calculates and sets the area.

Creating an Instance of Class 

The following statement creates an "instance" rect1 of class Rectangle.

            Rectangle rect1 = new Rectangle();




If we would have liked, we could have created three instance of the class Rectangle.

            Rectangle rect1 = new Rectangle();
            Rectangle rect2 = new Rectangle();
     Rectangle rect3 = new Rectangle(); 

Accessing methods of Class 

Here is how we access the methods of the class. The definerectangle(10, 20) sets the length and the breadth of the rectangle.The statement rect1.calculatearea() calculates the area of the instance rect1 of class Rectangle.

            rect1.definerectangle(10, 20);
            area1 = rect1.calculatearea();




We finally print the area of the rectangle using the Console.Writeline. This completes your initial understanding of classes. As an excercise you may like to create a class circle with a variable radius. You will also define two methodss area and perimeter for this class.



C# Classes - Public and Private variables



In some cases we want to have ability to modify the value of a variable from outside the class. To do this we precede the variable name with public keyword. 

Let us take a look at the following code 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Rectangle
{
    public int length, breadth;
    private int area;    
  
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            
            Rectangle rect1 = new Rectangle();
            rect1.length = 10;
            rect1.breadth = 20;
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}

If you run the above program you should be able to see the same output as the previous program. 



 
Area of Rectangle is 200



The difference is, this time we are able to assign the values of the variables of the class from the outside of the class. If you declare the variable as private, as in the following code it will report error.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Rectangle
{
    private int length, breadth;
  // Note that you can not assign the value of length and breadth out of class.
    private int area;    
  
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            
            Rectangle rect1 = new Rectangle();
            rect1.length = 10;  // Reprts error 
            rect1.breadth = 20;  // Reports error
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}



If you declare a variable private within a class, the only way to change or assign its value is from within the class.If you do not assign any thing public or private, by default it assumes them to be private. 

It is possible to assign the (default) values of some classes as soon as their instances are created. This is called constructor. We wil read them in the next page. 


C# Classes - Constructor



We may like to assign the values of the length and breadth as soon as we create the instance of the class. A constructor does that job.

Let us take a look at the following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Rectangle
{
    private int length, breadth;
    private int area;    

   
    public Rectangle(int length_input, int breadth_input)
    {
        length = length_input;
        breadth =  breadth_input;   
    }
     
       
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            
            Rectangle rect1 = new Rectangle(10, 20);
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}

If you run the above program you should be able to see the same output as the previous program.


 
Area of Rectangle is 200



The difference is, this time we are able to assign the values of the variables length and breadth as soon as we create an instance of the of the class Rectangle. This is done using the contructor

    public Rectangle(int length_input, int breadth_input)
    {
        length = length_input;
        breadth =  breadth_input;   
    }


A constructor is a special Method. It has the same name as the class. This special method gets automatically called when an instance of the class is created.

Take a look at how the instance of the class is created this time.

 Rectangle rect1 = new Rectangle(10, 20);





C# Namespaces



We have been using namespaces earlier. We hade made a brief mention of namespace in the begining. It is time to take a closer look at namespaces

A namespace contains a number of classes within them. Let us rewrite our earlier example and put the Rectancle class in a namespace shape1.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace shape1
{
class Rectangle
{
    private int length, breadth;
    private int area;    

   
    public Rectangle(int length_input, int breadth_input)
    {
        length = length_input;
        breadth =  breadth_input;   
    }  
       
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }
}

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            
            shape1.Rectangle rect1 = new shape1.Rectangle(10, 20);
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}



If you run the above program you still get the same output as the previous program.


 
Area of Rectangle is 200



There are two changes this time. First we have put the class Rectangle within the namespace shape1. Secondly, take a look at the way the instances of the class is created with shape1.Rectangle.


shape1.Rectangle rect1 = new shape1.Rectangle(10, 20);


So, what is the use of namespace ? Suppose you want to have two sets of class with same class name. You can distinguish them by putting them under different namespace. Each set of class is differentiated by preceding it by namespace. Let us learn it by example. I have talked rectangle enough times. You have bored. Let us talk about cars. Take a look at the example in which we have put same class name Car within two namespaces US and Japan.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace US
{
class Car
{
    public String name;
}
       
}

namespace Japan
{
    class Car
    {
        public String name;
    }

}


namespace ClassCar
{
    class Program
    {
        static void Main(string[] args)
        {
                       
            US.Car car1 = new US.Car();
            car1.name = "Ford";

            Japan.Car car2 = new Japan.Car();
            car2.name = "Toyota";
            
       
            Console.Write("US Car is ");
            Console.WriteLine(car1.name);

            Console.Write("Japan Car is ");
            Console.WriteLine(car2.name);

            Console.ReadLine();
        }
    }
}



If you run the above program you still get the same output as the previous program.


 
US Car is Ford
Japan Car is Toyota




We have put the class Car in two different namespaces US and Japan. This is helpful when you have a number of classes and you want to distinguish them.

Namespaces help you organize the code.It also helps to prevent clashes between two sets of class names. Using namespace is a good programming habit. It is not necessary for small codes, like those we have been doing here. But in real life when the codes size bigger you can think of its benefits.



C# Class - Static Members



We have seen that we need to create an instance of the class before we can use methods inside it. If you try to use a method of the class, it generates an error. The following program will therefore generate and error.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Car
{
    public void xyz()
    {
        Console.WriteLine("Referencedesigner tutorials are very bad");
    }
}  

namespace Printline
{
    class Program
    {
        static void Main(string[] args)
        {
            Car.xyz(); // This will generate an error
                       // Because instance of class Car was not created.   
            Console.ReadLine();
        }
    }
}


There are cases wherre we want to make the method global. We want to access the methods of the class without the need to create an instance of it. To do this we precede the method declaration with the keyword static. Here is the program that will work.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Car
{
    public  static  void xyz()
    {
        Console.WriteLine("Learning C# is easy with Reference Designer tutorials");
    }
}  

namespace Printline
{
    class Program
    {
        static void Main(string[] args)
        {
            Car.xyz(); 
            Console.ReadLine();
        }
    }
}



If we run the program we get the following result.

 
Referencedesigner tutorials are very bad



The static methods are kind of global methods to speak in the C or C++ terminology. Let us take a more useful example, where we want to provide a global method to calculate the area of the rectangle.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class rectangle
{
    public static int calculatearea (int x, int y)
    {
        return (x * y);
    }
}  

namespace Printline
{
    class Program
    {
        static void Main(string[] args)
        {
            int length, breadth, area;
            length = 10;
            breadth = 20;
            area = rectangle.calculatearea(length, breadth);
            Console.Write("Area of Rectangle is :");
            Console.Write(area); 
            Console.ReadLine();
        }
    }
}







If you run the above program you get the following output.


 
Area of Rectangle is :200




As you can see you can just call rectangle.calculatearea without the need to create instance of the class. This is helpful in many cases.


C# Arrays



Let assume that we have to calculate the area of 5 rectangles. We can declare 5 variables each for length and width and then another 5 variables for the area as follows.


    int length1,length2,length3,length4,length5;
    int breadth1,breadth2, breadth3,breadth4, breadth5;  
    int area1,area2, area3, area4,area5 ;    

  

While this is pefectly correct way to define the variables in this way, C# provides the concept of array.Here is how you do the same thing using arrays.



    int[] length;
    int[] breadth;  
    int[] area; 
   
  


The statement int[] length says that length is an array of type int. C# is different from other languages in that [] comes after the type instead of the identifier.

Let us now go ahead an write a program that will print the areas of 5 rectangles.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayExample
{
        class Program
    {      
        static void Main(string[] args)
        {
            int[] length;
            int[] breadth;
            int[] area;

            length = new int[5];
            breadth = new int[5];
            area = new int[5];

            int i;

            length[0] = 10; length[1] = 20; length[2] = 30; length[3] = 40; length[4] = 50;
            breadth[0] = 5; breadth[1] = 15; breadth[2] = 25; breadth[3] = 35; breadth[4] = 45;

            for (i = 0; i <= 4; i++)
            {
                area[i] = length[i] * breadth[i];
                Console.Write("Area = ");
                Console.WriteLine(area[i]);
            }

            Console.ReadLine();

        }
    }
}


  

If we execute this example we get the following output


 
Area = 50
Area = 300
Area = 750
Area = 1400
Area = 2250



Arrays help organize the codes. The statements


            length = new int[5];
            breadth = new int[5];
            area = new int[5];
  
  

create instance of the array types. Now instead of length1, length2, length3, length4 and length5 we have length[0],length[1],length[2],length[3],length[4]. Note that the array index starts from 0 and not 1.

Hiç yorum yok: