Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Shriram Institute of Information Technology, Paniv

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 !

➢ Compilation of the program –


1) The .Net framework has one or more language compliers, such as Visual Basic, C#, Visual
C++, JScript, or one of many third-party compilers such as an Eiffel, Perl, or COBOL compiler.

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.

Prof. Honrao Charushila Prakash (1 )


Shriram Institute of Information Technology, Paniv

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

Prof. Honrao Charushila Prakash (2 )


Shriram Institute of Information Technology, Paniv

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.

The following example makes this clear:-


using System;
namespace EgValueType
{

Prof. Honrao Charushila Prakash (3 )


Shriram Institute of Information Technology, Paniv

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

After Line 1 After Line 2 After Line 3 After Line 5


Stack Stack Stack Stack

num2 num2 num2 num2


0 0 5 3
num1 num1 num1 num1
0 5 5 5

Here, num1 & num2 each contains a copy of its own value.

Prof. Honrao Charushila Prakash (4 )


Shriram Institute of Information Technology, Paniv

Value Types defined by CTS are:-


C# Type Bits
bool System.Boolean 1
byte System.Byte 8
sbyte System.SByte 8
char System.Char 16
decimal System.Decimal 128
double System.Double 64
float System.Single 32
int System.Int32 32
uint System.UInt32 32
long System.Int64 64
ulong System.UInt64 64
short System.Int16 16
ushort System.UInt16 16

struct, enums are also value types.

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.

Prof. Honrao Charushila Prakash (5 )


Shriram Institute of Information Technology, Paniv

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

Prof. Honrao Charushila Prakash (6 )


Shriram Institute of Information Technology, Paniv

➢ 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;

----

----

Prof. Honrao Charushila Prakash (7 )


Shriram Institute of Information Technology, Paniv

Label 1: // Labeled Statement

// statement continuing execution from here

➢ Here label1is an identifier.


➢ goto statement transfer the program control directly to a labeled statement.
➢ A statement that has same label as that of the goto statement is known as labeled statement.
➢ One or more goto statement can transfer the program control to same labeled statement.
➢ goto transfer the control outside the control statement.
➢ E.g.: - while, do ... while, for loop.

➢ 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

Prof. Honrao Charushila Prakash (8 )


Shriram Institute of Information Technology, Paniv

➢ Some restrictions involved in goto statement are:


i. goto statement can’t jump into a block of code such as a for loop.
ii. goto statement can’t jump out of class.

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:-

Prof. Honrao Charushila Prakash (9 )


Shriram Institute of Information Technology, Paniv

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)
{

Prof. Honrao Charushila Prakash (10 )


Shriram Institute of Information Technology, Paniv

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

Square of Given number: 9

2. Iteration statement or loop:-

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);

Prof. Honrao Charushila Prakash (11 )


Shriram Institute of Information Technology, Paniv

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

b) do .... while loop:-


➢ The do...while loop is the post-test version of the while loop.

➢ 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.

Prof. Honrao Charushila Prakash (12 )


Shriram Institute of Information Technology, Paniv

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

Prof. Honrao Charushila Prakash (13 )


Shriram Institute of Information Technology, Paniv

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:-

for (initializer; condition; iterator)

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 iteration ends when the condition evaluates to false.


➢ The for loop is called as preset loop, because the loop condition evaluated before the loop statement
are executed.

Prof. Honrao Charushila Prakash (14 )


Shriram Institute of Information Technology, Paniv

➢ 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.

➢ This loop is specially designed to handle the elements of the collection.

➢ 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:-

foreach (type variable in collection)

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.

Prof. Honrao Charushila Prakash (15 )


Shriram Institute of Information Technology, Paniv

➢ 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.

➢ The loop ends when there are no more elements to obtain.

➢ 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:-

➢ Enum (Enumerator) is a user defined integer type.

➢ 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.

Prof. Honrao Charushila Prakash (16 )


Shriram Institute of Information Technology, Paniv

➢ 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.

➢ Enum types can be integer (float, int, byte, double etc).

➢ Enum is used to create numeric constant in .NET framework.

➢ All member of enum are of enum type. There must be a numeric value for each enum type.

The syntax to declare an enum is:

[Modifiers] enum identifier [: base-type]

Enumerator - list

➢ The default underlying type of the enumeration elements is int.

➢ By default, the first enumerator has the value 0, and the value of each successive enumerator is increased
by 1.

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

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:-

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};


In this enumeration the sequence of element is forced to start from 1 instead 0.

Program 1 -
using System;
namespace ConsoleApplication2
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

Prof. Honrao Charushila Prakash (17 )


Shriram Institute of Information Technology, Paniv

}
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 is a way to group a collection of classes & interface together.

➢ 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

Prof. Honrao Charushila Prakash (18 )


Shriram Institute of Information Technology, Paniv

➢ 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.

➢ To Access member of namespace –


The members of the namespace can be access with the dot (.) operator. Syntax is
Namespace_name.member_name;
Example
First.Hello h1 = new First.Hello();
h1.show();

Following program shows the use of namespace

e.g.

using System;
namespace FirsConsole
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hello, Namespace Example");
Console.Read();
}
}
}

Prof. Honrao Charushila Prakash (19 )


Shriram Institute of Information Technology, Paniv

Output -

Hello, Namespace Example.


Following program shows the multiple namespaces declared in a single

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");
}
}
}

public class TestNamespace


{
public static void Main()
{
First.Hello h1 = new First.Hello();
Second.Hello h2 = new Second.Hello();
h1.sayHello();
h2.show();
Console.ReadLine();
}
}

Output –
Hello First Namespace
Hello Second Namespace

Prof. Honrao Charushila Prakash (20 )


Shriram Institute of Information Technology, Paniv

➢ 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.

Prof. Honrao Charushila Prakash (21 )


Shriram Institute of Information Technology, Paniv

➢ 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

using Intro =MyNamespace;


namespace Demo
{
class Test
{
public static void Main(String[] Args)
{
Intro.Simple obj = new Intro.Simple();
Console.WriteLine(obj.GetNamespace());
Console.ReadLine();
}
}
}
namespace MyNamespace
{
class Simple
{
public string GetNamespace()
{
return "Welcome in My Namespace";
}
}
}
Output -
First.Second.Third
Welcome in Namespace aliase.

Prof. Honrao Charushila Prakash (22 )


Shriram Institute of Information Technology, Paniv

➢ The Main() Method –


The Main method is the entry point of a C# console application or windows application. When the
application is started, the Main method is the first method that is invoked. This Main() method is present in
every executable application. Executable means any Console application, Windows desktop application or
Windows service application.
In C# the execution of every program is start from Main () method. Every C# applications that
we write must have one class with a function called Main().
The Main() method is referred to as our applications entry point & the execution of our C#
application begins with the code in Main().
If our code contains more than one class, only one class can have a function called Main(). If we
forget to define a Main() method. We will receive several error from the compiler.
The C# compiler does, in fact, accept any of four possible constructs for the Main() function:-

public static void Main()s

public static void Main(String [] args)

public static int Main()

public static int Main(String [] args)

Here, the public is access specifier

➢ 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

Prof. Honrao Charushila Prakash (23 )


Shriram Institute of Information Technology, Paniv

{
static void Main(string[] args)
{
Console.WriteLine("Welcome Main method");
Console.Read();
}
}
}
Output –
Welcome Main method

➢ Multiple Main() Method –


C# has a strong feature in which we can define more than one class with the Main() method. When a C#
console or windows application is compiled, by default the compiler looks for exactly one Main() method in
any class matching the signature & makes that class method the entry point for the program.
If there is more than one Main() method, the compiler will return an error message.

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();
}
}

Prof. Honrao Charushila Prakash (24 )


Shriram Institute of Information Technology, Paniv

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;

Prof. Honrao Charushila Prakash (25 )


Shriram Institute of Information Technology, Paniv

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 -

Prof. Honrao Charushila Prakash (26 )


Shriram Institute of Information Technology, Paniv

➢ Method –

1) A Method contains a number of statements to perform a particular task.


2) A method can have any number of statements inside it.
3) In C#, every program must have a method named "Main". "Main" method is the starting point of a
program.
4) First, we define a method and then we make a call to use it.
5) The syntax of a method declaration is,

<access_specifier> <return_type> <method_name>()


{
//statement;
}

6) The following syntax show to call 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

Prof. Honrao Charushila Prakash (27 )


Shriram Institute of Information Technology, Paniv

➢ Parameter Passing Techniques –


Parameters can be passed to methods by reference or by value. When a variable is passed by reference,
the called method gets the actual variable, or more to the point, a pointer to the variable in memory. Any
changes made to the inside the method persists when the method exits.
However, when variable is passed by value, the called method gets an identical copy of the variable,
meaning any changes made are lost when the method exits.
1) Pass By Value -
This is the default mechanism for passing parameters to a method. In this mechanism when a
method is called, a new storage location is created for each value parameter. The values of the actual
parameters are copied into them. Hence, the changes made to the parameter inside the method have no
effect on the argument.
Example -
using System;
namespace MyProgram
{
class Program
{
public void Swap(int a,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();
Console.WriteLine("Before call swap function: ");
Console.WriteLine("n: "+n +" m: "+m);
p.Swap(n, m);
Console.WriteLine("After call swap function: ");
Console.WriteLine("n: " + n + " m: " + m);
Console.ReadLine();
}
}
}

Prof. Honrao Charushila Prakash (28 )


Shriram Institute of Information Technology, Paniv

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.

➢ In ref parameter passing technique parameter declared with a ref modifier.

➢ 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();

Prof. Honrao Charushila Prakash (29 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("Brfore call swap function: ");


Console.WriteLine("n: "+n +" m: "+m);
p.Swap(ref n, ref m);
Console.WriteLine("After call swap function: ");
Console.WriteLine("n: " + n + " m: " + m);
Console.ReadLine();
}
}
}

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);

Prof. Honrao Charushila Prakash (30 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("b: " + b);


}
static void Main(string[] args)
{
int n,m;
Console.Write("Enter Number: ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Number: ");
m = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Before function call values are: ");
Console.WriteLine("n: " + n);
Console.WriteLine("m: " + m);
Program p = new Program();
Console.WriteLine("After function call values are: ");
p.show(out n, out m);
Console.ReadLine();
}
}
}

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

4) params / parameter array –

➢ C# supports the use of parameter arrays.

➢ params keyword defines a method which can take variable number of arguments.

➢ This is also known as parameter arrays.

➢ 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.

➢ Only one params keyword is permitted in a method declaration.

Prof. Honrao Charushila Prakash (31 )


Shriram Institute of Information Technology, Paniv

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)
{

Program p = new Program();


p.show(10, 20, 30, 40, 50);
Console.ReadLine();
}
}
}

Output -
Total is:150

Prof. Honrao Charushila Prakash (32 )

You might also like