c#
c#
Net
Unit 1
INTRODUCTION:
The C# language
The .Net Architecture and .Net Framework
Understanding the HELLO WORLD Application Code,
Namespaces in C#
The using Keyword
The class Keyword
The Main() Method
Printing on the Console, Comments.
C# BASICS:
Data Types,
Variables & Constants,
Operators in C#,
Arithmetic Operators,
Prefix and Postfix notation,
Assignment Operators,
Relational Operators,
Other Operators,
Operators precedence,
Flow Control and Conditional Statements if-else statement,
switch statement,
Loops in C#,
for loop,
do-while loop,
Array in C#,
foreach Loop.
The C# language
Anders Hejlsberg is known as the founder of C# language.
C#(c-sharp) is a programming language developed by Microsoft that runs on the .NET Framework .
It is an Object Oriented Programming language and has at its core, many similarities to Java, C++ and
VB.
In fact, C# combines the power and efficiency of C++, the simple and clean OO design of Java and the
language simplification of Visual Basic.
Like Java, C# also does not allow multiple inheritance or the use of pointers (in safe/managed code),
C# provide garbage memory collection at runtime, type and memory access checking.
However, contrary to JAVA, C# maintains the unique useful operations of C++ like operator overloading,
enumerations, pre-processor directives, pointers (in unmanaged/un-safe code), function pointers (in the form
of delegates) and promises to have template support in the next versions.
Like VB, it also supports the concepts of properties (context sensitive fields).
In addition to this, C# comes up with some new and exciting features such as reflections, attributes,
marshalling, remoting, threads, streams, data access with ADO.Net and more.
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
VR
Database applications
And much, much more!
Remove the documentation comments (lines starting with ///), change the name of class from Class1 to
HelloWorld and write
Console.WriteLine("Hello World"); in place of //TODO: Add code....
to make the picture look like
using System;
namespace MyHelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
Now to compile and execute your application, select Debug - Start Without Debugging or press Ctrl+F5. This
will open a new Console Window with Hello World written in it. Once you press any key, the window will
close, terminating the program.
Namespaces in C#
A Namespace is simply a logical collection of related classes in C#.
We bundle our related classes (like those related with database activity) in some named collection calling it a
namespace (e.g., Data Activity).
As C# does not allow two classes with the same name to be used in a program, the sole purpose of using
namespaces is to prevent name conflicts.
This may happen when you have a large number of classes, as is the case in the Framework Class Library
(FCL).
It is very much possible that our Connection Class in DataActivity conflicts with the Connection Class of
Interne tActivity.
To avoid this, these classes are made part of their respective namespace. So the fully qualified name of these
classes will be Data Activity. Connection and Internet Activity. Connection, hence resolving any ambiguity
for the compiler.
So, in the second line of our program we are declaring that the following classes (within { } block) are part
of MyHelloWorldApplication namespace.
namespace MyHelloWorldApplication
{
...
}
Example
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Namespace!");
}
}
}
The C# namespaces have NO physical mapping as is the case in Java. Classes with same namespace can be
in different folders. The C# concept of mapping is similar to packages in Java and namespaces in standard
C++. The namespace may contain classes, events, exceptions, delegates and even other namespaces called
'Internal namespace'.
These internal namespaces can be defined like this:
namespace Parent
{
namespace Child
{
...
}
}
C#, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields)
and methods of a class. Also, braces () are used to identify methods in the code and string literals are enclosed
in double quotation marks ("). Lastly, each statement in C# (like C, C++ and Java) ends with a semicolon (;),
also called the statement terminator.
Comments
Comments are the programmer's text to explain the code, are ignored by the compiler and are not included in
the final executable code. C# uses syntax for comments that is similar to Java and C++. The text following
double slash marks (// any comment) are line comments. The comment ends with the end of the line:
Example
// This is my main method of programstatic void Main()
{
...
}
C# also supports the comment block. In this case, the whole block is ignored by the compiler. The start of the
block is declared by slash-asterisk (/*) and ends with asterisk-slash mark (*/):
static void Main()
{
/* These lines of text
will be ignored by the compiler */
}
C# BASICS
Data Types
There are two kinds of data types in C#.
Implicit data types are defined in the language core by the language vendor
explicit data types are types that are made by using or composing implicit data types.
Implicit data types are represented in language using keywords, so each of the above is a keyword in C#
(Keyword are the words defined by the language and can not be used as identifiers).
It is worth noting that string is also an implicit data type in C#, so string is a keyword in C#.
The last point about implicit data types is that they are value types and thus stored on the stack, while user
defined types or referenced types are stored using the heap.
A stack is a data structure that store items in a first in first out (FIFO) fashion. It is an area of memory
supported by the processor and its size is determined at the compile time.
A heap consists of memory available to the program at runtime.
Reference types are allocated using memory available from the heap dynamically (during the execution of
program). The garbage collector searches for non-referenced data in heap during the execution of program
and returns that space to Operating System.
Operators in C#
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Unary Operators
o Ternary Operators
Arithmetic Operators
Several common arithmetic operators are allowed in C#.
Operand Description
+ Add
- Subtract
* Multiply
/ Divide
% Remainder or modulo
++ Increment by 1
-- Decrement by 1
Example
using System;
namespace Arithmetic
{
class GFG
{
// Main Function
static void Main(string[] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);
// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
}
}
}
Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the
variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x.
And when it is placed after the variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution of the
next statement. For example, x++.
Decrement: The ‘- -‘ operator is used to decrement the value of an integer. When placed before the
variable name (also called pre-decrement operator), its value is decremented instantly. For example, --x.
And when it is placed after the variable name (also called post-decrement operator), its value is
preserved temporarily until the execution of this statement and it gets updated before the execution of the
next statement. For example, x--.
Example
using System;
namespace Arithmetic {
class GFG {
// Main Function
static void Main(string[] args)
{
int a = 10, res;
// post-increment example:
// res is assigned 10 only,
// a is not updated yet
res = a++;
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
// pre-increment example:
// res is assigned 11 now since a
// is updated here itself
res = ++a;
// a and res have same values = 11
Console.WriteLine("a is {0} and res is {1}", a, res);
// pre-decrement example:
// res is assigned 10 only since
// a is updated here itself
res = --a;
Assignment Operators
Assignment operators are used to assign values to variables. Common assignment operators in C# are:
Operand Description
= Simple assignment
+= Additive assignment
-= Subtractive assignment
*= Multiplicative
assignment
/= Division assignment
%= Modulo assignment
// it means x = x + 10
x += 10;
Console.WriteLine("Add Assignment Operator: " + x);
// it means x = x - 5
x -= 5;
Console.WriteLine("Subtract Assignment Operator: " + x);
// it means x = x * 5
x *= 5;
Console.WriteLine("Multiply Assignment Operator: " + x);
// it means x = x / 5
x /= 5;
Console.WriteLine("Division Assignment Operator: " + x);
// it means x = x % 5
x %= 5;
Console.WriteLine("Modulo Assignment Operator: " + x);
// it means x = x << 2
x <<= 2;
Console.WriteLine("Left Shift Assignment Operator: " + x);
// it means x = x >> 2
x >>= 2;
Console.WriteLine("Right Shift Assignment Operator: " + x);
// it means x = x >> 4
x &= 4;
Console.WriteLine("Bitwise AND Assignment Operator: " + x);
// it means x = x >> 4
x ^= 4;
Console.WriteLine("Bitwise Exclusive OR Assignment Operator: " + x);
// it means x = x >> 4
x |= 4;
Console.WriteLine("Bitwise Inclusive OR Assignment Operator: " + x);
}
}
}
Sometimes casting is used for type conversion, e.g., to convert and store a value in a variable of type double
to a variable of type int, we need to apply an integer cast.
double doubleValue = 4.67;
// intValue will be equal to 4
int intValue = (int) doubleValue;
Of course, when casting there is always a danger of some loss of precision; in the case above, we only got the
4 of the original 4.67. Sometimes, the casting may result in strange values:
int intValue = 32800;
short shortvalue = (short) intValue;
//short value would be equal to -32736
Variables of type short can only take values ranging from -32768 to 32767, so the cast above can not assign
32800 to shortValue. Hence shortValue took the last 16 bits (as a short consists of 16 bits) of the integer
32800, which gives the value -32736 (since bit 16, which represents the value 32768 in an int, now represents
-32768). If you try to cast incompatible types like:
bool isPaid = false;
int intValue = (int) isPaid;
It won't get compiled and the compiler will generate a syntax error.
Relational Operators
Relational operators are used for comparison purposes in conditional statements. Common relational
operators in C# are:
Operand Description
== Equality check
!= Un-equality check
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Relational operators always result in a Boolean statement; either true or false. For example if we have two
variables
int num1 = 5, num2 = 6;
num1 == num2 // false
num1 != num2 // true
num1 > num2 // false
num1 < num2 // true
num1 <= num2 // true
num1 >= num2 // false
Only compatible data types can be compared. It is invalid to compare a bool with an int, so if you have
int i = 1;
bool b = true;
you cannot compare i and b for equality (i==b). Trying to do so will result in a syntax error.
Example
using System;
namespace Relational {
class GFG {
// Main Function
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
The operators &, | and ^ are rarely used in usual programming practice. The NOT operator is used to negate
a Boolean or bitwise expression like:
bool b = false;
bool bb = !b;
// bb would be true
Logical Operators && and || are used to combine comparisons like
int i=6, j=12;
bool firstVar = i>3 && j<10;
// firstVar would be false bool secondVar = i>3 || j<10;
// secondVar would be true
In the first comparison: i>3 && j<10 will result in true only if both the conditions i>3 and j<10 result in
true. In the second comparison: i>3 || j<10 will result in true if any of the conditions i>3 and j<10 result in
true. You can, of course, use both && and || in single statement like:
bool firstVar = (i>3 && j<10) || (i<7 && j>10) // firstVar would be true
In the above statement we used parenthesis to group our conditional expressions and to avoid any ambiguity.
Example : logical operator
using System;
namespace Logical {
class GFG {
// Main Function
static void Main(string[] args)
{
bool a = true,b = false, result;
// AND operator
result = a && b;
Console.WriteLine("AND Operator: " + result);
// OR operator
result = a || b;
Console.WriteLine("OR Operator: " + result);
// NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}
Conditional Operator
It is ternary operator which is a shorthand version of if-else statement. It has three operands and hence the
name ternary. It will return one of two values depending on the value of a Boolean expression.
Syntax:
condition ? first_expression : second_expression;
using System;
namespace Conditional {
class GFG {
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
Other Operators
There are some other operators present in C#. A short description of these is given below:
Operand Description
. Member access for objects
[] Index operator used in arrays and
collections
() Cast operator
?: Ternary operator
Operator Precedence
All operators are not treated equally. There is a concept of "operator precedence" in C#. For example:
int i = 2 + 3 * 6;
// i would be 20 not 30
3 will be multiplied by 6 first then the result will be added to 2. This is because the multiplication operator *
has precedence over the addition operator +. For a complete table of operator precedence, consult MSDN or
the .Net framework documentation.
Category Operator Associativity
C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
}
}
C# IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true otherwise else
block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
}
}
nested if statement
Since if...else is also a statement, you can use it under other if...else statement (nesting), like
if(i>5)
{
if(i==6)
{
Console.WriteLine("Ok, 6 is close to 5.");
}
else // line 7
{
Console.WriteLine("Oops! I'm older than 5 but not 6!");
}
Console.WriteLine("Thank God, I finally became older than 5.");
}
else // line 13
{
Console.WriteLine("Missed...When will I become 5 or close to 5?");
}
C# IF-else-if ladder Statement
The C# if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());
switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
}
There are some important points to remember when using the switch...case statement in C#:
case "Pakistan":
continent ="Asia";
Console.WriteLine("Pakistan is an Asian Country");
break;
default:
continent = "Un-recognized";
Console.WriteLine
("Un-recognized country discovered");
break;
The end of the case and default statements is marked with break (or goto) statement. We don't use {}
brackets to mark the block in switch...case as we usually do in C#
C# does not allow fall-through. So, you can't leave case or default without break statement (as you can in
Java or C/C++). The compiler will detect and complain about the use of fall-through in the switch...case
statement.
The break statement transfers the execution control out of the current block.
Statements under default will be executed if and only if all the case checks fail.
It is not necessary to place default at the end of switch...case statement. You can even place the default
block before the first case or in between cases; default will work the same regardless of its position.
However, making default the last block is conventional and highly recommended. Of course, you can't
have more than one default block in a single switch...case.
Loops In C#
Loops are used for iteration purposes, i.e., doing a task multiple times (usually until a termination condition is
met)
Loops are mainly divided into two categories:
Entry Controlled Loops: The loops in which condition to be tested is present in beginning of loop body
are known as Entry Controlled Loops. while loop and for loop are entry controlled loops.
The for Loop
for loops are preferred when the number of times loop statements are to be executed is known beforehand.
The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is
done in one line in for loop thereby providing a shorter, easy to debug structure of looping.
The C# for loop is same as C/C++. We can initialize variable, check condition and increment/decrement
value.
Syntax:
for(initialization; condition; incr/decr){
//code to be executed
}
Example
using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
Console.WriteLine(i);
}
}
}
C# Nested For Loop
In C#, we can use for loop inside another for loop, it is known as nested for loop. The inner loop is executed
fully when outer loop is executed one time. So if outer loop and inner loop are executed 3 times, inner loop
will be executed 3 times for each outer loop i.e. total 9 times.
using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
Console.WriteLine(i+" "+j);
}
}
}
}
If you don't use the {} brackets, the statement immediate following for() will be treated as the iteration
statement. The example below is identical to the one given above:
for(int i=1; i<=10; i++)
Console.WriteLine("In the loop, value of i is {0}.", i);
C# While Loop
In C#, while loop is used to iterate a part of the program several times. If the number of iteration is not fixed,
it is recommended to use while loop than for loop.
The test condition is given in the beginning of the loop and all statements are executed till the given
Boolean condition satisfies when the condition becomes false, the control will be out from the while
loop.
Syntax:
while(condition){
//code to be executed
}
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=10)
{
Console.WriteLine(i);
i++;
}
}
}
Exit Controlled Loops: The loops in which the testing condition is present at the end of loop body are
termed as Exit Controlled Loops. do-while is an exit controlled loop. Note: In Exit Controlled Loops,
loop body will be evaluated for at-least one time as the testing condition is present at the end of loop body
do-while loop
The C# do-while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
do while loop is similar to while loop with the only difference that it checks the condition after executing
the statements, i.e it will execute the loop body one time for sure because it checks the condition after
executing the statements.
There is a semicolon ; after the while statement.
Syntax:
do{
//code to be executed
}while(condition);
Example
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;
do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;
}
}
do{
int j = 1;
do{
Console.WriteLine(i+" "+j);
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}
}
Arrays in C#
Array Declaration
An Array is a collection of values of a similar data type.
Technically, C# arrays are a reference type.
Each array in C# is an object and is inherited from the System.Array class.
Arrays are declared as:
<data type> [] <identifier> = new <data type>[<size of array>];
int [] integers = new int[10];
The size of an array is fixed and must be defined before using it. However, you can use variables to define the
size of the array:
int size = 10;
int [] integers = new int[size];
It is also possible to define arrays using the values it will hold by enclosing values in curly brackets and
separating individual values with a comma:
int [] integers = {1, 2, 3, 4, 5};
This will create an array of size 5, whose successive values will be 1, 2, 3, 4 and 5.
C# Array Types
There are 3 types of arrays in C# programming:
1. Single Dimensional Array
2. Multidimensional Array
3. Jagged Array
C# Single Dimensional Array
To create single dimensional array, you need to use square brackets [] after the type.
int[] arr = new int[5];//creating array
You cannot place square brackets after the identifier.
int arr[] = new int[5];//compile time error
Example
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or three
dimensional. The data is stored in tabular form (row * column) which is also known as matrix.
To create multidimensional array, we need to use comma inside the square brackets. For example:
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr=new int[3,3];//declaration of 2D array
arr[0,1]=10;//initialization
arr[1,2]=20;
arr[2,0]=30;
//traversal
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
//traversal
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
C# Jagged Arrays
In C#, jagged array is also known as "array of arrays" because its elements are arrays. The element size of
jagged array can be different.
Declaration of Jagged array
int[][] arr = new int[2][];
Initialization of Jagged array
Let's see an example to initialize jagged array. The size of elements can be different.
arr[0] = new int[4];
arr[1] = new int[6];
Initialization and filling elements in Jagged array
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Example
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the array
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
foreach Loop
The foreach loop is used to iterate over the elements of the collection. The collection may be an array
or a list. It executes for each element present in the array.
It is necessary to enclose the statements of foreach loop in curly braces {}.
Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type
as the base type of the array, followed by a colon, which is then followed by the array name.
In the loop body, you can use the loop variable you created rather than using an indexed array element.
There is another type of loop that is very simple and useful to iterate through arrays and collections. This is
the foreach loop. The basic structure of a foreach loop is
Syntax
foreach(<type of elements in collection> <identifier> in <array or collection>)
{
// statements to be executed
}
Example
using System;
class GFG {
// Main Method
static public void Main()
{
Console.WriteLine("Print array:");
// creating an array
int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };
The variable used to hold the individual elements of array in each iteration (items in the above example) is
read only. You can't change the elements in the array through it. This means that foreach will only allow you
to iterate through the array or collection and not to change the contents of it. If you wish to perform some
work on the array to change the individual elements, you should use a for loop.
foreach can be used to iterate through arrays or collections. By a collection, we mean any class, struct or
interface that implements the IEnumerable interface
The string class is also a collection of characters (implements IEnumerable interface and returns char value
in Current property). The following code example demonstrates this and prints all the characters in the
string.