Professional Documents
Culture Documents
Unit - 2 VP-1
Unit - 2 VP-1
Unit – II
C# Basics
➢ C# Language –
C# (Pronounced as ‘C Sharp’) is a computer Programming Language developed by Microsoft
Corporation, USA. C# is fully object oriented language and it is first Component-Oriented language. It is a
simple, modern, and efficient and type safe language derived from the popular C & C++ language. Although it
belongs to the modern language suitable for developing web based, windows & console application.
Simple Program in C#-
using System;
namespace HelloWorld
{
class Program
{
static void Main(String[] args)
{
Console.WriteLine("Hello World !");
Console.Read();
}
}
}
Output:-
Hello World !
2) Source code (C# or VB.Net) is compiled into Microsoft Intermediate Language (MSIL) code
with the help of language specific compiler.
E.g.:- CSC compiler for C# and VBC compiler for VB.Net.
3) "Microsoft Intermediate Language" (MSIL) code is also known as "Intermediate Language"
(IL) Code or "Common Intermediate Language" (CIL) Code.
4) C# compiler translates source code into MSIL/IL/CIL code.
5) MSIL code is stored in file called Assembly. This assembly is created after the successful
compilation of application.
6) Since MSIL code cannot be executed directly, because it's not in a machine-executable format,
the CLR compiles the MSIL using the Just-In-Time (JIT) compiler (or JITter) into native CPU
instructions. The JIT compiling occurs only as methods in the program are called. The
compiled executable code is cached on the machine and is recompiled only if there's some
change to the source code.
7) This native executable code is then processed by machines processor.
➢ Variables –
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C# has a specific type, which determines the size and layout of the variable's memory the range of
values that can be stored within that memory and the set of operations that can be applied to the variable.
1) Defining Variable –
Syntax for variable definition in C# is –
<data_type> <variable_list>;
Where
data_type must be a valid C# data type including char, int, float, double, or any user-defined data type,
and variable_list may consist of one or more identifier names separated by commas.
e.g.
int a,b;
char str;
2) Initialization of Variables -
Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is −
variable_name = value;
Variables can be initialized in their declaration. The initialize consists of an equal sign followed
by a constant expression as −
<data_type> <variable_name> = value;
e.g.
int a;
a=10;
int c=10, d=20;
char str=’S’;
➢ Data Type –
In C#, data type can be derived into two categories that is –
1) Value Type
2) Reference Type
1) Value Type –
Value type variables can be assigned a value directly. They are derived from the
class System.ValueType. The value types directly contain data. Value Type directly contains actual
data on stack. They cannot contain null value.
Some examples are int, char, and float, which stores numbers, alphabets, and floating
point numbers, respectively. When you declare an int type, the system allocates memory to store the
value.
class Program
{
static void Main(String[] args)
{
/*Line 1*/ int num1, num2;
/* Line 2*/ num1 = 5;
/* Line 3*/ num2 = num1;
/* Line 4*/ Console.WriteLine("Num1 is {0}. Num2 is {1}", num1, num2);
/* Line 5*/ num2 = 3;
/* Line 6*/ Console.WriteLine("Num1 is {0}. Num2 is {1}", num1, num2);
/* Line 7*/ Console.Read();
}
}
}
Output:-
Num1 is 5. Num2 is 5
Num1 is 5. Num2 is 3
Here, num1 & num2 each contains a copy of its own value.
2) Reference Type –
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
In other words, they refer to a memory location. For reference types, the variable stores a
reference to the data rather than the actual data. The reference is stored on stack, while the actual object
is created on managed heap. Reference type can be null.
Reference types defined in CTS are:-
Object, String, Classes, Interfaces, Array, and Delegates.
Example:-
int weight = 70; weight 70
String title = “.NET”; title
.NET
When Reference type is assigned to another reference type, one the reference is copied & not the value.
The actual value remains in the same memory location. This means that there are two references to a
single value.
Program:-
using System;
namespace EgReferenceType
{
class abc
{
public int value = 0;
}
class Test
{
public static void Main(String[] Args)
{
int val1 = 0;
int val2 = val1;
val2 = 123;
abc x = new abc();
abc x1 = x;
x1.value = 123;
Console.WriteLine("Value : {0} {1}", val1, val2);
Console.WriteLine("Refs : {0} {1}", x.value, x1.value);
Console.Read();
}
}
}
Output:-
Value : 0 123
Refs : 123 123
➢ Flow Control -
Flow Control statements are used to change the flow of execution of a program. In C# the Flow
Control statements are divided into 3 categories, which are as follows:-
1) Selection statement / Decision making:-
Executes a block of code only when certain condition or a set of condition is true. A condition is
boolean expressions, which are defined inside the parenthesis of a selection statement.
a) C# support two types of selection statements:-
a) if statement
b) switch statement
2) Iteration statements or loops:-
Executes a specific block of code as long as long as, a certain condition is true. This means an
iteration statement or loop executes a statement or a set of statement in a repeated manner.
In C#, there are the following four types of iteration statement –
a) While loop
b) do .... while loop
c) for loop
d) foreach loop.
3) Jump Statement:-
Transfer the program control from one block of code to another.
There are five types of jump statement, which are as follows
a) goto statement
b) break statement
c) continue statement
d) return statement
e) throw statement
a) goto statement:-
The Statement enables us to jump directly to another specified line in the program, indicated by
label.
Syntax:-
goto label1;
----
----
➢ Program:-
using System;
namespace gotostatement
{
class abc
{
static void Main(String[] Args)
{
int sum = 0;
for (int i = 1; i <= 10; i++)
{
if (i >= 5)
{
goto siit;
}
Console.WriteLine(i);
sum = sum + i;
}
siit:
Console.WriteLine("Sum:" + sum);
}
}
}
Output:-
1
2
3
4
Sum:10
iii. We can’t exit a finally block after the try..... Catch blocks.
b) break statement :-
➢ Break statements are used to break (exit) a loop. Break statement terminates a loop in which it appears.
➢ Commonly we use it to exit from a case in a switch statement.
➢ Break can be used to exit from for, foreach, while or do.... while loops.
➢ Control will switch to the statement immediately after the end of the loop.
➢ Program:-
using System;
namespace breakstatement
{
class Program
{
static void Main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
if (i >= 5)
break;
}
Console.Read();
}
}
Output:-
The restriction of break statement is we can’t use it outside of a switch statement or a loop, a
compile time error will occur.
c) Continue Statement :-
➢ It transfer the program control to the next iteration of loop in which the continue statement appears.
➢ Continue statement starts a new iteration of enclosing loop.
➢ It exists only from current iteration of loop, meaning that execution will restart at the beginning of the
next iteration of loop.
➢ Continue statement is used within a for, foreach, while or do....while loop.
Program:-
using System;
namespace Continuestatement
{
class Program
{
static void Main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i <= 5)
continue;
Console.WriteLine(i);
}
Console.Read();
}
}
}
Output:-
6
7
8
9
10
d) Return statement :-
➢ The return statement terminate (exit) the execution of the method in which it appears and return control
to the calling method.
➢ If method has a return type, return must return a value of this type; otherwise, if the method returns void,
we should use return without an expression.
Program:-
class Square
{
public int showsquare(int n)
{
return n * n;
}
}
class Program
{
static void Main(string[] args)
{
int a, result;
Console.Write("Enter Number: ");
a = Convert.ToInt32(Console.ReadLine());
Square s = new Square();
result = s.showsquare(a);
Console.WriteLine("Square of Given number: " + result);
Console.ReadLine();
}
}
Output:-
Enter Number: 3
a) while loop :-
➢ While loop is a pretest loop.
➢ It executes a statements or group of statements while a given condition is true.
➢ It tests condition before executing the loop body.
➢ The iteration ends when the condition evaluates to false.
➢ It is called pretest loop because the loop condition is evaluated before the loop statement are executed
Syntax:-
While (condition)
{
Statement(s);
Entry
False
Condition
True
Statement
Program:-
using System;
namespace Whileloop
{
class Program
{
static void Main(String[] args)
{
int sum = 0;
int n = 1;
while (n <= 10)
{
sum = sum + n * n;
n++;
}
Console.WriteLine("Sum: " + sum);
Console.Read();
}
}
}
Output:-
Sum: 385
➢ This means that the loops test condition is evaluated after the body of loop has been executed.
➢ Consequently, do......while loops are useful for situation in which a block of statement must be
executed at least one time.
➢ In this loop the body of statement is executed first and then condition is checked.
Syntax:-
do
Statement(s);
} while (condition);
Start
Executes block of
statements
Condition
True
False
Program:-
using System;
namespace DoWhileloop
{
class Program
{
static void Main(String[] args)
{
int sum = 0;
int n = 1;
do
{
sum = sum + n * n;
n++;
} while (n <= 10);
Console.WriteLine("Sum: " + sum);
Console.Read();
}
}
}
Output: Sum: 385
c) for loop :-
➢ It is repetition control structure that allows us to efficiently write a loop that needs to execute a
specific number of times.
Syntax:-
Statement(s);
Where,
➢ The initializer is the expression evaluated before the first loop is executed, it initialize a local
variable as a loop counter.
➢ The condition is the expression checked before each new iteration of the loop. If the condition is
false the loop is exited, otherwise if true the body of statement is executed.
➢ The iterator is an expression executed after each iteration (usually incrementing/decrementing the
loop counter).
Initialiazer
False
Condition
True
Execute
Statements
Increment /
Decrement
➢ The for loop is excellent for repeating a statement or a block of statement for a predetermined
number of times.
Program:-
using System;
namespace Forloop
{
Output:-
10
11
12
13
14
15
d) foreach loop:-
➢ The foreach loop is similar to the for loop, but implemented differently.
➢ Collection represents a group of elements, e.g. array is a collection which stores a group of element
like integer and strings.
➢ The foreach loop repeatedly executes a group of statements for each element of the collections.
➢ This means foreach loop is used to iterate through each elements in arrays and collections.
Syntax:-
Body of loop
➢ Here, types and variable declare the iteration variable. During execution, the iteration variable represents
the array elements for which iteration is currently being performed. The type must be the same as the
element type of the array or it should be object type.
➢ When loop begins, the first element in the array is obtained & assigned to variable. Each subsequent
iteration obtains the next element from the array & stored it in variable.
➢ Thus the foreach cycles through the array one element at a time, from start to finish.
➢ Here, Iteration variable is a read only, means we can’t change the contents of an array by assigning the
iteration variable a new value.
Program:-
using System;
namespace Foreachloop
{
class ForeachDemo
{
static void Main(String[] args)
{
int[] a = {11, 22, 33, 44, 55 };
foreach (int i in a)
{
Console.WriteLine(i);
}
Console.Read();
}
}
}
Output:-
11
22
33
44
55
➢ Enumeration –
Introduction:-
➢ Which provide a way for attaching name to numbers, thus increasing the flexibility of code.
➢ An enum is a value type with a set of related named constant often referred to as an enumerated list.
➢ The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
➢ If you place constants directly where used, your C# program become complex. It becomes hard to
change. Enum instead keep these magic constant in a distinct type. They improve code clarity. They
reduce maintenance issues.
➢ All member of enum are of enum type. There must be a numeric value for each enum type.
Enumerator - list
➢ By default, the first enumerator has the value 0, and the value of each successive enumerator is increased
by 1.
In this enumeration Sat is 0, Sun is 1, Mon is 2 and so forth. Enumeration can have initializers to
override the default values. For example:-
Program 1 -
using System;
namespace ConsoleApplication2
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
public static void Main(String[] args)
{
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Sunday, DayofWeek.Sunday);
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Monday,DayofWeek.Monday);
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Tuesday,DayofWeek.Tuesday);
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Wednesday,
DayofWeek.Wednesday);
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Thursday, DayofWeek.Thursday);
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Friday, DayofWeek.Friday);
Console.WriteLine("Day Of Week {0} {1}", (int)DayofWeek.Saturday,DayofWeek.Saturday);
Console.Read();
}
}
}
Output:-
Day Of Week 1 Sunday
Day Of Week 2 Monday
Day Of Week 3 Tuesday
Day Of Week 4 Wednesday
Day Of Week 5 Thursday
Day Of Week 6 Friday
Day Of Week 7 Saturday
➢ Namespace –
➢ Namespace in .NET are used to organize classes & other types into a single hierarchical structure.
➢ A Namespace defines a declarative region that provides a way to keep one set of names separate from
another. In essence, names declared in one Namespace will not conflict with the same names in another
➢ Namespace are defined using the Namespace statement. For multiple levels of organization Namespace can
be nested.
➢ Declaring a Namespace:
A Namespace is declared using the namespace keyword. Classes to be including in the namespace must be
declared within the namespaces curly brackets.
Syntax:-
namespace name
{
Members
}
Here, name is the name of the namespace. Anything defined within a Namespace is within the scope of
that namespace. Thus namespace defines the scope. Within the namespace we can declare classes, structure,
delegate, enumeration, interface or another namespace.
e.g.
using System;
namespace FirsConsole
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hello, Namespace Example");
Console.Read();
}
}
}
Output -
using System;
namespace First
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello First Namespace");
}
}
}
namespace Second
{
public class Hello
{
public void show()
{
Console.WriteLine("Hello Second Namespace");
}
}
}
Output –
Hello First Namespace
Hello Second Namespace
➢ Nested Namespace –
A namespace can contain another namespace. It is called nested namespace. The nested namespace and
its members can also be accessed using the dot(.) operator.
Syntax –
namespace MyNamespace
{
namespace NestedNamespace
{
// Body of nested namespace
}
}
Example -
using System;
namespace First
{
namespace second
{
public class sample
{
public void show()
{
Console.WriteLine("Welcome in nested namespace");
}
}
}
}
namespace MyProgram
{
class Program
{
static void Main(string[] args)
{
First.second.sample s = new First.second.sample();
s.show();
Console.ReadLine();
}
}
}
Output –
Welcome in nested namespace.
➢ Namespace Aliases:-
If program have a very long namespace name that we want to refer to several times in our code but
don't want to include in a simple using statement, we can assign an alias to the Namespace.
In other word namespace aliases use of alias name in place of longer namespace and it provides a
way to avoid ambiguous definitions of the classes.
using alias = NamespaceName;
Here, alias becomes another name for the class or namespace specified by namespacename.
e.g.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Namespce Alias
➢ Static keyword declares that the Main() method is a global one & can be called without creating an instance
(object) of the class. The compiler stores the address of the method as the entry point & uses this
information to begin execution before any objects are created.
➢ The keyword void tells the compiler that Main() does not return value and int tell Main() method return
integer value.
➢ The String [] args used to pass command line arguments to the Main() Method at runtime.
e.g.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace First
{
class F
{
static void Main(string[] args)
{
Console.WriteLine("Welcome Main method");
Console.Read();
}
}
}
Output –
Welcome Main method
e.g
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyProgram
{
class Program
{
public static void Main(string[] args)
{
Console.Write("Welocme, First Main Method");
Console.Read();
}
}
class MyClass
{
public static void Main(string[] args)
{
Console.Write("Welocme, Second Main Method");
Console.Read();
}
}
}
To clear issue use following steps –
1) Go to Project Menu -> Properties -> Application Tab -> Startup object.
2) Select one class name those you want to execute. Save your application and run the program.
3) If I select MyClass the output will display “Welocme, First Main Method”.
4) Or if you select Program the output will display “Welocme, Second Main Method”.
Or Passing Command Line Arguments / Passing Arguments to Main():-
If user use the command prompt to run application then write program in Notepad and save it with the
extension with .cs and open command prompt follow following steps.
Eg. MainMethod.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyNamespace
{
class First
{
static void Main(string[] args)
{
Console.WriteLine("Welcome first Main method");
Console.Read();
}
}
class Second
{
static void Main(string[] args)
{
Console.WriteLine("Welocme second Main method");
Console.Read();
}
}
1) To compile
csc <program name.cs> /main:<namespace name>.<class name>
e.g.
csc myprogram.cs / main:mynamespace.MyClass
2) To run
<program name>
e.g.
MainMethod
Output -
➢ Method –
<method_name>();
Example –
using System;
namespace MyProgram
{
class Program
{
public void MyMethod()
{
Console.WriteLine("Welcome in my method");
}
static void Main(string[] args)
{
Program p = new Program();
p.MyMethod();
Console.ReadLine();
}
}
}
Output –
Welcome in my method
Output –
Enter first number: 20
Enter second number: 30
Before call swap function:
n:20 m:30
After call swap function:
n: 20 m:30
2) ref parameters –
➢ The ref parameter modifier causes C# to create a call-by-reference, rather than a call-by-value.
➢ The ref parameters pass reference of a storage location instead of actual value.
➢ Parameter to be passed as ref parameter should be initialized before it is passed into a method.
➢ When parameters are passed using ref, method to refer to the same variable that was passed into the
method.
➢ Any changes made to the parameter in the method will be reflected in that variable when control passes
back to the calling method.
➢ This Means, ref parameter represents the same storage location, instead of creating a new storage
location for the variable given as the argument in the method invocation.
Example -
using System;
namespace MyProgram
{
class Program
{
public void Swap(ref int a, ref int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int n, m;
Console.Write("Enter first number: ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
m = Convert.ToInt32(Console.ReadLine());
Program p = new Program();
Output –
Enter first number: 20
Enter second number: 30
Before call swap function:
n:20 m:30
After call swap function:
n: 30 m:20
3) out parameter –
➢ The out parameters pass reference of the storage location instead of actual value.
➢ In out parameter passing techniques parameter declared with a out parameter.
➢ The out parameter can be used to return the values to the same variable passed as a parameter to
the method.
➢ It represents the same storage location, instead of creating a new storage location for the variable
given as the argument in the method invocation.
➢ It is same as ref parameter except the fact the parameter passed as out need not be initialized
before it is passed into method. But they have to be assigned some value before control return to
calling method.
➢ Multiple values can be returned using out parameter.
Example –
using System;
namespace MyProgram
{
class Program
{
public void show(out int a, out int b)
{
a = 100;
b = 200;
Console.WriteLine("a: " + a);
Output –
Enter Number: 20
Enter Number: 30
Before function call values are:
n: 20
m: 30
After function call values are:
a: 100
b: 200
➢ params keyword defines a method which can take variable number of arguments.
➢ No additional parameters are permitted after the params keyword in a method declaration.
➢ A params parameter must always be the last parameter defined in a method declaration.
➢ Before params keyword we can add multiple parameters to the method.
Example -
using System;
namespace MyProgram
{
class Program
{
public void show(params int[] listNo)
{
int total = 0;
foreach (int i in listNo)
{
total = total + i;
}
Console.WriteLine("Total is: " + total);
}
static void Main(string[] args)
{
Output -
Total is:150