Skip to content
Home » Programming » C# for Beginners » C# for Beginners

C# for Beginners

C# for beginners

Introduction

C# is pronounced as “C-Sharp”. It’s an object-oriented programming language initially created by Microsoft that runs on the .NET Framework. It has roots from the C family, & the language is close to other popular languages like C, C++ and Java. The first version was released in year 2002.

C# is used for the for followings:

1. Desktop applications
2. Web applications
3. Database applications
4. Mobile applications
5. Web sites
6. Web services
7. Games

Integrated Development Environment (IDE) For C#

Mostly following development tools are use for C# programming:
Visual Studio (VS)
Visual C# Express (VCE)
Visual Web Developer

C# Program Structure

Before we begin basic building blocks of the C# programming language, let us look at minimum C# program structure.

C# Hello World Example

Basically, C# consists of the following parts.

  1. Namespace declaration
  2. A class
  3. Class methods
  4. Class attributes
  5. A Main method
  6. Statements & Expressions
  7. Comments
using System;
namespace HelloWorldApplication
{
       class HelloWorld
      {
            static void Main(string[] args)
            {
                  /* my first program in C# */
                  Console.WriteLine("Hello World");
                  Console.ReadLine();
            }
      }
}
Output:
Hello World

Compilation

Type csc helloworld.cs & press enter to compile the code.
If there are no errors in our code the command prompt will take us to the next line and would generate helloworld.exe executable file.

C# Basic Syntax

C# is an object oriented programing language. In OOP methodology a program consists of various objects that interact with each other by means of actions. Methods are the action that an object may take.. Objects of same kind are said to have same type or, more often, are said to be in same class.
For example, let us assume a Rectangle object that has attributes like length & width. Depending upon the design, it might need ways to accept values of these attributes, calculating area & display details.

using System;
namespace RectangleApplication
{
      class Rectangle
      {
            // member variables
            double length;
            double width;
            public void Acceptdetails()
            {
                  length = 4.5;
                  width = 3.5;
            }
            public double GetArea()
            {
                  return length * width;
            }
            public void Display()
            {
                  Console.WriteLine("Length: {0}", length);
                  Console.WriteLine("Width: {0}", width);
                  Console.WriteLine("Area: {0}", GetArea());
            }
      }

      class ExecuteRectangle
      {
            static void Main(string[] args)
            {
                  Rectangle r = new Rectangle();
                  r.Acceptdetails();
                  r.Display();
                  Console.ReadLine();
            }
      }
}

The class Keyword

Class keyword is used for declaring a class.

Member Variables

Variables are attributes or data members of a class, used for storing data.

Member Functions

Functions are the set of statements that perform the specific task. The member functions of class are declared within the class. Our sample class Rectangle contains three member functions:
AcceptContact, GetDetails and Display.

Instantiating a Class

In the above program, the class ExecuteRectangle is used as a class which contains the Main() method and instantiates the Rectangle class.

Identifiers

An identifier is the name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in C# are listed below:

  1. A name must start with a letter which can be followed by a sequence of letters, digits (0 – 9) or underscore. A digit can’t be used as the first character in an identifier.
  2. Space or symbol like aren’t allowed.
    But, an underscore ( _ ) can be used.
  3. C# keyword is not allowed.

C# Keywords

Keywords are the reserved words predefined to C# compiler. Keywords cannot be used as identifiers.
But, if we want to use these keywords as identifiers, we may prefix the keyword with @ character. In C#, some identifiers have special meaning in context of code; like get and set; which are called contextual keywords.

The table below lists the reserved keywords in C#:

abstractasBaseboolbreakbytecase
catchcharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitexternfalsefinallyfixedfloatfor
foreachgotoifimplicitinintinterface
internalislocklongnamespacenewnull
objectoperatoroutoverrideparamsprivateprotected
publicreadonlyrefreturnsbytesealedshort
sizeofstackallocstaticstringstructswitchThis
throwtruetrytypeofuintulongunchecked
unsafeushortusingvirtualvoidvolatilewhile

C# Data types

In C#, the variables are categorized into:

  1. Value types
  2. Reference types
  3. Pointer types

1. Value types

Value type variables can be assigned as value directly. They are derived from the class System.ValueType.
The value types directly contain data. Some examples are char, float, int, which stores alphabets, numbers and floating point numbers respectively. When we declare an float type, the system allocates memory to store the value.

The table below lists the available value types in C#.

Diferent vaue-type in C# with their representations, range and default value.

To get size of type or variable on a particular platform, we can use the “sizeof” method.
The expression sizeof(type) returns the storage size of the object or type in bytes.
For example,

namespace DataTypeApplication
{
      class Program
      {
            static void Main(string[] args)
            {
                  Console.WriteLine("Size of int: {0}", sizeof(int));
                  Console.ReadLine();
            }
      }
}

2. Reference Types

The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables that means they refer to a memory location. The reference types can refer to a memory location by using more than one variable. When data in the memory location is changed by one of the variables, the other variable automatically reflects that change in value. Examples of built in reference types are: string, object and dynamic.

Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System. Object class. So object types can be assigned values of any other predefined or user-defined types; however, before assigning values, it needs type conversion.

When a value type is converted to object type, then it is called boxing. On the other hand, when an object type is converted to a value type, then it is called unboxing.

object obj;
obj = 100; // this is boxing

Dynamic Type
Any type of value can be stored in the dynamic data type variable. For these types of variables, type checking takes place at runtime. Syntax for declaring a dynamic type is: dynamic <variable_name> = value;
For example,

dynamic d = 20; 

Dynamic types are similar to object types.
Except that, type checking for object type variables takes place at compile time, whereas those for the dynamic type variables take place at run time.

String Type
The String Type allows us to assign any string values to a variable. The string type is an alias for
the System.String class. It is derived from object type. Value for the string type can be assigned
using string literals in 2 forms they are quoted and @quoted.

For example

String str = "First String"; 

A @quoted string literal looks like:
@”First String”;
The user defined reference types are: delegate, interface, or class.

3. Pointer Type

Pointer type variables is for storing the memory address of another type.
In C#, Pointers have the same capabilities as in C or C++.
Syntax for declaring a pointer type is:

type* identifier;
char* cptr;
int* iptr;

C# Type Conversition

Type conversion is type casting or converting one type of data to another type.
In C#, type casting has 2 forms:

  1. Implicit type conversion – These type of conversions are performed by C# in a type-safe manner. Examples: conversions from smaller to larger integer types.
  2. Explicit type conversion – Users using the pre-defined functions do these type conversions explicitly.
    Explicit conversions require a cast operator.

    The following example shows an explicit type conversion:
namespace TypeConversionApplication
{
      class ExplicitConversion
      {
            static void Main(string[] args)
            {
                  double d = 5673.74;
                  int i;
                  // cast double to int.
                  i = (int)d;
                  Console.WriteLine(i);
                  Console.ReadLine();
            }
      }
}
Output:
5673

C# Type Conversion Methods

Basically, C# provides the following built-in type conversion methods:

  1. ToBoolean: It converts a type to a Boolean value.
  2. ToByte: It converts a type to a byte.
  3. ToChar:It converts a type to a single Unicode character, where possible.
  4. ToDateTime: It converts a type to date_time structures.
  5. ToDecimal: It converts a floating point or integer type to a decimal type.
  6. ToDouble: It converts a type to a double type.
  7. ToInt16: It converts a type to 16-bit integer.
  8. ToInt32: It converts a type to a 32-bit integer.
  9. ToInt64: It converts a type to a 64-bit integer.
  10. ToSbyte: It converts a type to a signed byte type.
  11. ToSingle: It converts a type to a small floating_point number.
  12. ToString: It converts a type to string.
  13. ToType: It converts a type to specified type.
  14. ToUInt16: It converts a type to an unsigned int type.
  15. ToUInt32: It converts a type to an unsigned long type.
  16. ToUInt64: It converts a type to an unsigned big integer.

The following example will convert various value types to string type.

namespace TypeConversionApplication
{ 
      class StringConversion
      {
            static void Main(string[] args)
            {
                  int i = 75;
                  float f = 53.005f;
                  double d = 2345.7652;
                  bool b = true;
                  Console.WriteLine(i.ToString());
                  Console.WriteLine(f.ToString());
                  Console.WriteLine(d.ToString());
                  Console.WriteLine(b.ToString());
                  Console.ReadLine();
            }
      }
}
Output:
75
53.oo5
2345.7652
True

C# Variables

A variable is just a name that is given to a storage area that our programs can manipulate. Each variable in C# has a specific type that determines size and layout of variable’s memory; the range of values that can be stored within that memory; and set of operations that can be applied to variable. We have already discussed various data types. Basic value types in C# can be categorized as:

TypeExample
Integral typesbyte, sbyte, ushort, short, uint, int, ulong, long and char
Floating point typesfloat and double
Decimal typesdecimal
Boolean typestrue or false values, as assigned
Nullable typesNullable data types

Variable Declaration in C#

In C#, syntax for variable declaration is:’;’. Data_type must be valid C# data type and variable_list may consist of one or more identifier names separated by commas. Valid variable declarations along with their definition are:

int i, j, k;
char c, ch;
float f, salary;
double d;

Variable Initialization in C#

Variables are initialized/assigned a value with an (=) sign followed by a constant expression. The general form of initialization is:
variable_name = value;
Variables is initialized/assigned an initial value in their declaration. The initializer consists of an (=) sign followed by constant expression as:
<data_type><variable_type> = value;

Some examples are:

int d = 3, f = 5; /* initialize d and f. */
byte z = 22; /* initialize z. */
double pi = 3.14159; /* declare an approximation of pi. */
char x = 'x'; /* variable x has the value 'x'. */

Following example makes use of various types of variables:

namespace VariableDeclaration
{
      class Program
      {
            static void Main(string[] args)
            {
                  short x;
                  int y ;
                  double z;
                  /* actual initialization */
                  x = 10;
                  y = 20;
                  z = x + y;
                  Console.WriteLine("x = {0}, y = {1}, z = {2}", x, y, z); /*print result*/
                  Console.ReadLine();
            }
      }
}
Output:
a =10, b = 20, c = 30

Accepting Values from User

The Console class in the System namespace provides the function ReadLine() to accept input from user & store it into a variable. int num;

num = Convert.ToInt32(Console.ReadLIne());

The function Convert.ToInt32() converts data entered by user to int data type.
Because Console.ReadLine() accepts the data in string format.

Lvalues and Rvalues in C#

There are two kinds of expressions in C#:

  1. lvalue : An expression that is an lvalue may appear as either the right-hand or left-hand side of an assignment.
  2. rvalue : An expression that is an rvalue may appear only on right-hand side. But not on left-hand side of an assignment.

    Variables are lvalues. So may appear on left-hand side of an assignment. Numeric literals are rvalues. So may not be assigned & cannot appear on the left-hand side. Following is a valid statement:
    int g = 20;
    But following is not the valid statement & can generate compile-time error:
    10 = 20;

C# Constants and Literals

The constants are used to fix values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an a character constant, integer constant, a floating constant, or a string literal. There are also enumeration constants as well.

The constants are just like regular variables except that their values can’t be modified after
their definition.

Integer Literals

An integer literal can be any such as octal, decimal, or hexadecimal constant. A prefix specifies base : 0x or 0X for hexadecimal, 0 for octal, & nothing for an integer literal can also have a suffix which is the combination of U & L, for unsigned & long, respectively. The suffix can be uppercase or lowercase & can be in any order.
Here are some examples of integer literals:

212 / * Legal */
215u / * Legal */
0xFeeL / * Legal */
078 / * Illegal: 8 is not an octal number */
032UU / * Illegal: can't repeat a suffix */
Other examples of various types of Integer literals:
85 / * decimal */
0213 / * octal */
0x4b / * hexadecimal */
30 / * int */
30u / *unsigned int * /
30l / * long */
30ul / * unsigned long */

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, & an exponent part.
Floating point literals can be reppresented either in decimal form or exponential form.
Here are some examples of floating-point literals:

3.14159 /* Legal */
314159E-5L / * Legal */
510E / * Illegal: incomplete exponent */
210f / * Illegal: no decimal or exponent */
.e55 / * Illegal: missing integer or fraction */

When representing using decimal form, we must include decimal point, exponent, or both. And while representing using exponential form we must include integer part, fractional part, or both. The signed exponent is represented by e or E.

Character Constants

Character literals are enclosed in single quotes. e.g., ‘x’. It can be stored in simple variable of char-type. Character literal can be a plain character. (e.g. ‘x’), An escape sequence (e.g., ‘\t’), or a universal character (e.g. ‘\u02C0’).
There’re certain characters in C# when they’re proceeded by a back slash they’ll have special meaning & they’re used to represent like newline (\n) or tab (\t). Here you’ve a list of some of such escape sequence codes:

Escape sequenceMeaning
\\\ character
\’‘ character
\”” character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\oooOctal number of one to three digits
\xhh . . .Hexadecimal number of one or more digits

String Literals

String literals ( constants ) are enclosed in double quotes “” or with @””. A string contains characters which are similar to character literals: escape sequences, plain characters, & universal characters.
We can break a long line into multiple lines using string literals & separating the parts using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"

Defining Constants

Constants are defined using the const keyword. Syntax to define a constant is:
const <data_type> <constant_name>= value;
The following program illustrates defining &using a constant in your program:

using System;
namespace DeclaringConstants
{
      class Program
      {
            static void Main(string[] args)
            {
                  const double pi = 3.14159; // constant declaration
                  double r;
                  Console.WriteLine("Enter Radius: ");
                  r = Convert.ToDouble(Console.ReadLine());
                  double areaCircle = pi * r * r;
                  Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
                  Console.ReadLine();
            }
      }
} 
Output:
Enter Radius
3
Radius: 3, Area: 28.27431

C# Operators

An operator is defined as a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# is rich in built-in operators & provides the following type of operators:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Misc Operators

Arithmetic Operators

Following table gives all the arithmetic operators supported by C#. Let variable A holds 1 & variable B holds 2 then:

OperatorsDescriptionExample
+it adds two operandsA + B will give 3
it subtracts second operand from the firstA – B will give -1
*it multiplies both operands A * B will give 2
/it divides numerator by de-numeratorB / A will give 2
%Modulud Operator and remainder of after an integer divisionB % A will give 0
++Increment operator increases integer value by oneA++ will give 2
Decrement operator decreass integer value by 1A– will give 0

Relational Operators

Following table gives all the relational operators supported by C#. Consider variable A holds 1 &variable B holds 2 then:

Operator DescriptionExample
==It’ll check if the value of two operands is equal or not. If yes then condition becomes true.(A==B) s not true.
!=It’ll checks if the value of two operands is equal or not. If values aren’t equal then condition becomes true.(A!=B) is true.
>It’ll check if the value of left operand is greater than the value of right operand. If yes then the condition becomes true.(A>B) is not true.
<It’ll check if the value of left operand is less than or equal to the value of right operand. If yes then the condition becomes true.(A<B) is true.
>=It’ll check if the value of left operand is greater than or equal to the value of right operand. If yes then the condition becomes true.(A>=B) is no true.
<=It’ll check if the value of left operand is less than or equal to the value of right operand. If yes then the condition becomes true.(A<=B) is true.

Logical Operators

Following table gives all the logical operators supported by C#. Suppose variable A holds Boolean value true & variable B holds Boolean value false then:

OperatorDescriptionExample
&&Called Logical AND operator. If both operands are found non-zero, then condition becomes true.(A&&B) is false.
||Called Logical OR operator. If any of the operands is non zero then condition becomes true.(A||B) is true.
!Called Logical NOT operator. It’ll reverse the logical state of its operand. If a condition is true then Logical NOT will make false.!(A&&B) is true.

Bitwise Operators

Bitwise operator works on bits & performs bit-by-bit operation. The truth tables for &, |, & ^ are as follows:

PQP&QP|QP^Q
00000
01011
11110
10011

Suppose if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
using System;
namespace OperatorsAppl
{
      class Program
      {
            static void Main(string[] args)
            {
                  int x = 60; /* 60 = 0011 1100 */ /*value of x is declared 60*/
                  int y = 13; /* 13 = 0000 1101 */ /*value of y is declared 13*/
                  int z = 0;
                  z = x & y; /* 12 = 0000 1100 */
                  Console.WriteLine("Line 1 - Value of z is {0}", c); /**prints output*/
                  z = x | y; // 61 = 0011 1101
                  Console.WriteLine("Line 2 - Value of z is {0}", c); /**prints output*/
                  z = x ^ y; /* 49 = 0011 0001 */
                  Console.WriteLine("Line 3 - Value of z is {0}", c); /**prints output*/
                  z = ~x ; //-61 = 1100 0011
                  Console.WriteLine("Line 4 - Value of z is {0}", c); /**prints output*/
                  z = x << 2; /* 240 = 1111 0000 */
                  Console.WriteLine("Line 5 - Value of c is {0}", c); /**prints output*/
                  c = a >> 2; /* 15 = 0000 1111 */
                  Console.WriteLine("Line 6 - Value of z is {0}", c); /**prints output*/
                  Console.ReadLine();
            }
      }
}
Output:
Line 1 - = Value of z = 21
Line 2 - += Value of z = 42
Line 3 - -= Value of z = 21
Line 4 - *= Value of z = 441
Line 5 - /= Value of z = 21
Line 6 - %= Value of z = 11
Line 7 - <<= Value of z = 44 Line 8 - >>= Value of c = 11
Line 9 - &= Value of z= 2
Line 10 - ^= Value of z = 0
Line 11 - |= Value of z = 2

Assignment Operators

OperatorDescriptionExample
=It is simple assignment operator, it’ll assign values from right side operands to left side operandC = A + B will assign value of A + B into C
+=It is Add AND assignment operator, it’ll add right operand to the left operand & assign the result to left operandC += A is equivalent to C = C + A
-=It is Subtract AND assignment operator, this’ll subtract right operand from the left operand & assign the result to left operandC -= A is equivalent to C = C – A
*=It is Multiply AND assignment operator, it’ll multiply right operand with the left operand & assign the result to left operandC *= A is equivalent to C = C * A
/=It is Divide AND assignment operator, it’ll divide left operand with the right operand & assign the result to left operandC /= A is equivalent to C = C / A
%=It is Modulus AND assignment operator, it’ll take modulus using two operands & assign the result to left operandC %= A is equivalent to C = C % A
<<=This is Left shift AND assignment operator.C <<= 2 is same as C = C << 2
>>=This is Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=This is Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=This is Bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=This is Bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Misc Operators

There’re few other important operators including sizeof, typeof & ? : supported by C#.

Operator DescrptionExample
sizeof()This’ll return the size of a datatype.sizeof(int), will return 4.
typeof()This’ll return the type of a class.typeof(StreamReader);
&This’ll return the address of an variable.&a; will give actual address of the variable.
*Pointer to the variable.*a; will point to the variable.
?:Conditional ExpressionIf Condition is true? Then value X : Otherwise value Y
isDetermine whether an object is of a certain type.If (Ford is Car) // checks if Ford is an object of the Car calss.
asThis’ll cast without raising an exception if the cast fails.Object obj = new StringReader(“Hello”);
StringReader r = obj as StringReader;

C# Decision Making

In C#, decision making means the programmer define one or more conditions to be (tested)checked by the program, along with the statement or statements to be executed if the condition is true. And optionally, other statements to be executed ifthe condition is false. C# provides following types of decision making statements.

If statement

An if statement contains a boolean expression followed by one or more statements. Syntax:
The syntax of an if statement in C# is given below:

if(boolean_expression)
{
      /* statement(s) to be executed when the boolean expression is true */
}

If the boolean expression values to true then the block of code inside the if statement will be executed. If boolean expression values to false then the first set of code after the end of the if statement will be executed.

If…else statement

An if statement followed by an optional else statement. It is executed when the boolean expression is false.

Syntax:
if(boolean_expression)
{
     /* statement(s) to be executed when the boolean expression is true / } else { /
     statement(s) to be executed when the boolean expression is false */
}

If the boolean expression values to true then the if block of code will be executed otherwise else block of code will be executed.

The if…else if…else Statement

The if…else if…else Statement
An if statement followed by an optional else if…else statement & it is very useful to test various conditions using single if…else if statement.
Few points to keep in mind when using if , else if , else statements

  1. An if can have zero or one else’s & it must come after any else if’s.
  2. An if can have zero or many else if(s) & they must come before the else.
  3. Once an else if succeeds, none of the remaining else or else if(s) will be tested.
Syntax:
if(boolean_expression 1)
{
     /* It is executed when the boolean expression 1 is true / }
     else if( boolean_expression 2) { / Executed when the boolean expression 2 is true / } 
     else if( boolean_expression 3) { / 
     It is executed when the boolean expression 3 is true / } else { / executes when the none of 
     the above condition is true */
}

Nested if statements

It is always legal in C# to nest if-else statements, which means we can use one if or else if statement inside another if or else if statement(s).

Syntax:
if( boolean_expression 1)
{
     /* Execute when the boolean expression 1 is true / if(boolean_expression 2) { / Execute
      when the boolean expression 2 is true */
     }
}

Switch statement

A switch statement allows a variable to be checked for equality against a list of values. Each value is called a case, & the variable being switched on is checked for each switch case.

Syntax:
switch(expression){
     case constant-expression :
     statement(s);
     break; /* optional / case constant-expression : statement(s); break; / optional / 
     / We can have any number of case statements / default : / Optional */
     statement(s);
}

The ? : Operator:

It has the following general form.

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, & Exp3 are expressions. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated & becomes the value of the entire ? expression. If Exp1 is false. Then Exp3 is evaluated & its value becomes the value of the expression.

C# Loops

Sometimes, there may be a situation when we need to execute a block of code several number of times. In general, statements are executed sequentially. First statement in a function is executed first,then second & so on.

A loop statement permits to execute a statement or group of statements multiple times & followings are the general form of a loop statement:

While loop

A while loop statement in C# repeatedly executes statement(s) as long as a given condition is true.

Syntax:
while(condition)
{
     statement(s);
}

Here, statement(s) may be either a single statement or a block of statements. The condition may be any expression. True is any nonzero value.
The loop iterates while the condition is true.
If the condition becomes false, the program control passes to the line immediately following the loop.

for loop

A for loop is a repetition control structure. It allows us to efficiently write a loop that needs to execute a specific number of times.

Syntax:
for ( init; condition; increment )
{
     statement(s);
}

do…while loop

Unlike for & while loops, which test the loop condition at the top of the loop, the do…while loop checks its condition at the bottom of the loop.
A do…while loop is similar to a while loop, but a do…while loop is guaranteed to execute at least one time.

Syntax:
do
{
     statement(s);
}while( condition );

If the condition is true, the flow of control jumps back up to do, & the statement(s) in the loop
execute again. This process will repeat until the given condition becomes false

Nested loops

C# lets us to use one loop inside another loop.

Syntax:
for ( init; condition; increment )
{
     for ( init; condition; increment )
     {
          statement(s);
     }
     statement(s);
}

Example: Program to find the prime numbers less than 100.

using System;
namespace Loops
{
      class Program
      {
            static void Main(string[] args)
            {
                  /* local variable definition */
                  int i, j;
                  for (i = 2; i < 100; i++)
                  {
                          for (j = 2; j <= (i / j); j++) 
                          {
                                  if ((i % j) == 0) break; /* if factor found, not prime if (j >(i / j)) */
                          }
                          Console.WriteLine("{0} is prime", i);
                 }
                 Console.ReadLine();
            }
      }
}

Loop Control Statements:

Some control statements in C# are:

break statement

The break statement has 2 usage.

  1. When the break statement appears inside the loop, the loop is immediately terminated & program control resumes at the next statement following the loop.
  2. It can also be used to terminate a case in the switch statement.
    If we are using nested loops, the break statement’ll stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax:
break;

continue statement

In C#, the continue statement works somewhat like the break statement.
Break forces termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test & increment portions of the loop to execute.
For the while & do…while loops, continue statement causes the program control passes to the conditional tests.

Syntax:
continue;

C# Array

An array stores a fixed-size sequential collection of elements of the same datatype.
It is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same datatype.
All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element & the highest address to the last element.

Declaring Arrays

In C#, you can use the following syntax to declare aray: datatype[] arrayName;
where,
1. datatype is used to specify the type of elements to be stored in the array.
2. [ ] specifies the rank of the array. The rank specifies the size of the array.
3. arrayName specifies the name of the array.

Example
double[] balance;

Initializing and assigning values to an Array

Declaring an array doesn’t initialize the array in the memory.
When the array variable is initialized, we can assign values to the array.
Array is a reference type, so we need to use the new keyword to create an instance of the array.

double[] balance = new double[10];
double[] balance = new double[10];
balance[0] = 4500.0;

1. We can assign values to the array at the time of declaration.
Like: double[] balance = { 2340.0, 4523.69, 3421.0};

2. We can also create and initialize an array.
Like: int [] marks = new int[5] { 98, 97, 91, 98, 94};

3. In the preceding case, we may also omit the size of the array.
Like: int [] marks = new int[] { 98, 97, 91, 98, 94};

4. Also, we can copy an array variable into another target array variable.
In that case, both the target & source would point to the same memory location:
int [] marks = new int[] { 98, 97, 91, 98, 94};
int[] score = marks;

Accessing Array Elements

Indexing the array name accesses an element. Placing the index of the element within square brackets after the name of the array does this.
For example: double salary = balance[9];

Two-Dimensional Arrays

The simplest form of the multi-dimensional array is the 2-dimensional array.

A 2-dimensional array is, in essence, a list of 1-dimensional arrays.
A 2 dimensional array can be thought of as a table which will have x number of rows & y number of columns.

Initializing Two-Dimensional Arrays

Specifying bracketed values for each row may initialize multi-dimensional arrays.

Following is an array with 3 rows & each row has 4 columns.
int [,] a = int [3,4] = {
{0, 1, 2, 3} , /* This is initializers for row indexed by 0 / {4, 5, 6, 7} , / This is initializers for row indexed by 1 / {8, 9, 10, 11} / This is initializers for row indexed by 2 */
};

Accessing Two-Dimensional Array Elements

Using the subscripts ie accesses an element in 2-dimensional array. row index & column index of the array.
For example: int val = a[2,3];
Here, the above statement will take 2nd element from the 3rd row of the array.

C# Classes

Whenever we define a class, we define a blueprint for a data-type.
This doesn’t actually define any data, but it does define what the class name means, i.e. what an object of the class will consist of & what operations can be performed on that object. Objects are instances of a class. The methods & variables that constitute a class are called members of the class.

Class Definition

A class definition starts with the keyword class followed by the class name, & the class body, enclosed by a pair of curly braces. General form of a class definition is:

class class_name
{
     // member variables
     variable1;
     variable2;
     …
     variableN;
          // member methods
     method1(parameter_list)
     {
          // method body
     }
     method2(parameter_list)
     {
          // method body
     }
     … 
     methodN(parameter_list)
    {
          // method body
    }
}

Please note that,

  1. Access specifier specifies the access rules for the members as well as the class itself.
    If it is not mentioned, then the default access specifier for a class type is internal.
    Default access for the members is private. Data type specifies the type of variable, & return type specifies the data type of the data, the method returns, if any.
  2. To access the class members, we will use the dot (.) operator.

3 .The dot(.) operator links the name of an object with the name of a member.

Member Functions and Encapsulation

A member-function of a class is a function. It has its definition or its prototype within the class definition like other variable. It operates on any object of the class of which it is a member, & has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) & they’re kept private to implement encapsulation. These variables are only accessed using the public member functions.

The following example program can demonstrate this concept.

using System;
namespace BoxApplication
{
      class Box
      {
            private double length; // Length of a box
            private double breadth; // Breadth of a box
            private double height; // Height of a box

            public void setLength( double len )
            {
                  length = len;
            }
            public void setBreadth( double bre )
            {
                  breadth = bre;
            }
            public void setHeight( double hei )
            {
                  height = hei;
            }
            public double getVolume()
            {
                  return length * breadth * height;
            }
      }

      class Boxtester
      {
            static void Main(string[] args)
            {
                  Box Box1 = new Box(); // Declares  Box1 of type Box
                  Box Box2 = new Box();// Declares Box2 of type Box
                  double volume;
                  // box 1 specification
                  Box1.setLength(6.0);
                  Box1.setBreadth(7.0);
                  Box1.setHeight(5.0);
                  // box 2 specification
                  Box2.setLength(12.0);
                  Box2.setBreadth(13.0);
                  Box2.setHeight(10.0);
                  // volume of box 1
                  volume = Box1.getVolume();
                  Console.WriteLine("Volume of Box1 : {0}" ,volume);
                  // volume of box 2
                  volume = Box2.getVolume();
                  Console.WriteLine("Volume of Box2 : {0}", volume);
                  Console.ReadLine();
            }
      }
}
Output:
Volume of Box1 : 210
Volume of Box2 : 1560

C# Collections

Collection classes are specialized classes for data storage & retrieval that provide support for stacks, queues, lists, & hash tables. Most collection classes implement the same interfaces. Collection classes serve various purposes, like allocating memory dynamically to elements and accessing a list of items on the basis of an index etc.
These classes create collections of objects of the Object class, that is the base class for all data types in C#.

Various Collection Classes and Their Usage

The various commonly used classes of the System.Collection namespace are:

ArrayList :
It represents ordered collection of an object which can be indexed individually. It is basically an alternative to an array. But unlike array we can add & remove items from a list at a specified position using an index & the array resizes itself automatically. It also allows dynamic memory allocation, add, search & sort items in the list.

Hashtable:
It uses a key to (access)obtain the elements in the collection. A hash table is used when we need to access elements by using key. We can identify a useful key value. In the hash table, every item has a key/value pair. The key is used to retrieve the items in the collection.

Sortedlist:
It uses a key as well as an index to retrieve the items in a list.
A sorted list is a combination of an array & a hash table. It contains a list of item which can be accessed using a key or an index.
If we access items using an index, it is an ArrayList, and if we access items using a key , it is a Hashtable. The collection of items is always arranged by the key value.

Stack:
It represents a last-in, first-out (LIFO) collection of object.
It is used when we need a last-in, first-out access of items.
When we add an item in the list, it is called pushing the item and when you remove it, it is calledpopping the item.

Queue:
It represents a first-in, first-out (FIFO)collection of object.
It is used when we need a first-in, first-out access of items.
When we add an item in the list, it is called enqueue.
When we remove an item, it is called deque.

Bitarray:
It represents an array of the binary representation using the values 1 & 0.
It is used when we need to store the bits but do not know the number of bits in advance.
We can (access)obtain items from the BitArray collection by using an integer index, which starts from zero.

Example of an Arraylist

using System;
using System.Collections;
namespace CollectionApplication
{
      class Program
      {
            static void Main(string[] args)
            {
                  ArrayList al = new ArrayList();
                  Console.WriteLine("Adding some numbers:");
                  al.Add(46);
                  al.Add(78);
                  al.Add(33);
                  al.Add(56);
                  al.Add(12);
                  al.Add(23);
                  al.Add(9);
                  Console.WriteLine("Capacity: {0} ", al.Capacity);
                  Console.WriteLine("Count: {0}", al.Count); 
                  Console.Write("Content: ");
                  foreach (int i in al)
                  {
                        Console.Write(i + " ");
                  }
                  Console.WriteLine();
                  Console.Write("Sorted Content: ");
                  al.Sort();
                  foreach (int i in al)
                  {
                  Console.Write(i + " ");
                  }
                  Console.WriteLine();
                  Console.ReadKey();
            }
      }
}
Output:
Adding some numbers:
Capacity: 8
Count: 7
Content: 46 78 33 56 12 23 9
Sorted Content: 9 12 23 33 46 56 78

Leave a Reply

Your email address will not be published. Required fields are marked *