0% found this document useful (0 votes)
23 views57 pages

Unit 2 - DOT - NET - CORE

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views57 pages

Unit 2 - DOT - NET - CORE

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Shriram Institute of Information Technology, Paniv

Unit – II
Object Oriented Programming

Class –
A class combines the fields and methods (member function which defines actions) into a single unit. A
class is a way to bind data and its associated function together. A class is a template for an object and an object
is an instance of a class. C# is a true object-oriented language & therefore the underlying structure of all c#
programs is classes. A class provides a definition for dynamically created instances of the class, also known
as objects. Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and
specialize base classes.

 Declaration of Class -
A class declaration consists of a class header and body. The class header includes attributes, modifiers,
and the class keyword. The class body encapsulates the members of the class, which are the data members and
member functions. A class is a user-defined data type with a template that serves to define its properties.
Classes are declared by using the class keyword.

Syntax:-
class classname

[Variable declaration;]

[Methods declaration;]
}
Here, class is a keyword and classname is any valid c# identifier. Everything inside the square brackets is
optional.

A c# class may include many more items, such as properties, indexers, constructors, destructors and operators.

 Access Modifiers / Specifiers:-


Access Modifiers are keywords that define the accessibility of a member, class or
datatype in a program. These are mainly used to restrict unwanted data manipulation by external
programs or classes. There are 4 access modifiers (private , public, protected and internal).

Prof. Honrao Bhagyashri Prakash (1 )


Shriram Institute of Information Technology, Paniv

1) private
2) public :-
3) protected
4) internal

1) private:-
Private Access Specifier is used to specify private accessibility to the variable or function. It is
most restrictive and accessible only within the body of class in which it is declared.
Syntax:
private TypeName;
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
private string model = "Dot NET Core";

static void Main(string[] args)


{
Program myObj = new Program();
Console.WriteLine(myObj.model);
Console.Read();
}
}
}
Output:
Dot NET Core

2) public:-
The public keyword is an access modifier, which is used to set the access level/visibility
for classes, fields, methods and properties. The code is accessible for all classes. Access is
granted to the entire program. This means that another method or another assembly which
contains the class reference can access these members or types.

Prof. Honrao Bhagyashri Prakash (2 )


Shriram Institute of Information Technology, Paniv

Syntax:
public TypeName;

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

namespace ConsoleApplication1
{
class Car
{
public string model = "Dot NET Core";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
Console.Read();
}
}
}
Output:
Dot NET Core

3) protected:-
It is accessible within the class and has limited scope. It is also accessible within sub
class or child class, in case of inheritance.

Example: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
public class Program
{

Prof. Honrao Bhagyashri Prakash (3 )


Shriram Institute of Information Technology, Paniv

protected void Test1()


{
Console.WriteLine("This is Protected Data Member...");

}
static void Main(string[] args)
{
Program p = new Program();
p.Test1();
Console.Read();
}
}
}

Output: -
This is Protected Data Member...

4) internal:-
The internal keyword is used to specify the internal access specifier for the variables and
functions. This specifier is accessible only within files in the same assembly.
Example: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class InternalTest
{
internal string name = "All...";
internal void Msg(string msg)
{
Console.WriteLine("Subject Name : " + msg);
}
}
public class Program
{
static void Main(string[] args)
{
InternalTest internalTest = new InternalTest();
Console.WriteLine("Hello " + internalTest.name);
internalTest.Msg("Dot NET Core");

Prof. Honrao Bhagyashri Prakash (4 )


Shriram Institute of Information Technology, Paniv

Console.Read();
}
}
}

Output: -
Hello All...
Subject Name : Dot NET Core

 Creating Object -
Object is instance of class. An object in c# is essentially a block of memory that contains space to store
all the instance variables. Creating an object is also referred to as instantiating an object.

Objects in c# are created using new operator. A new operator creates objects of the specified class and
returns a reference to that object.

Syntax -
Class_name object_name;

object_name = new class_name();

OR
class_name object_name = new class_name ();

Here is an example of creating an object of type Rectangle.

Rectangle rect; //declare


rect = new Rectangle (); //instantiate
Here first statement declares a variable to hold the object reference (address) and the second one
actually assigns the reference to the variable. The variable rect is now an object of the Rectangle class.
The new operator allocates memory dynamically and assigns reference of this location to
variable of type class.
Both statements can be combined into one as:-

Rectangle rect = new Rectangle ();


The object rect does not contains the value for the Rectangle object; it contains only the
reference (i.e. address) to the object.

Prof. Honrao Bhagyashri Prakash (5 )


Shriram Institute of Information Technology, Paniv

The method Rectangle () is the default constructor of the class.

Action Statement Result

Declare Rectangle rect; Null rect

Declare rect = new Rectangle (); rect

Rectangle
Object

Fig.:- Creating objects references.

Each object has its own copy of the instance variable of its class. This means that any changes to the
variables of one object have no effect on the variable of another.

We can also assign an object to an object, like the following-

Rectangle r1 = new Rectangle ();

Rectangle r2 = r1;

r1

Rectangle
r2 Object

Here, both r1 and r2 refer to the same object. Any changes made to one object will be reflected in the
other objects.

 Accessing class member –


Each object contains its own set of variables. We should assign values to these variables in order to use
them in program. All variables must be assigned values before they are used.
Since we can‟t access the instance variables & methods outside the class directly to do this we must use
the concerned object & the dot (.) operator.

Prof. Honrao Bhagyashri Prakash (6 )


Shriram Institute of Information Technology, Paniv

Syntax:
objectname.variablename;

objectname.methodname (parameter list);

Here objectname is the name of the object, variablename is the name of the instance variable inside the
object that we wish to access, methodname is the method that we wish to call & parameter list is the comma
separated list of actual values that must match in type & number with the parameter list of the methodname
declared in the class.

Example:-

Rectangle rect1= new Rectangle ();

rect1.getdata (15, 10);

Program –
using System;
namespace ClassObject
{
class Sample
{
public int a, b;
public void getdata(int x, int y)
{
a = x;
b = y;
}
public void display()
{
int c = a + b;
Console.WriteLine("Addition is: " + c);
}
}
class Program
{
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());
Sample s = new Sample();
s.getdata(n, m);
s.display();
Console.ReadLine();
}

Prof. Honrao Bhagyashri Prakash (7 )


Shriram Institute of Information Technology, Paniv

}
}

Output -
Enter First Number: 5
Enter Second Number: 20
Addition is: 25

Class Member –
Classes have members that represent their data and behavior. A class's members include all the members
declared in the class. The fields and methods (member function which defines actions) inside classes are
referred class members.
1) Fields - Variables inside the class are called as field and that you can access them by creating an object of
the class, and by using the dot syntax (.)
Syntax –
Objectname.field;
Example –
Sample s=New Sample();
s.num;
Program –
using System;
namespace ClassObject
{
class Book
{
public int a = 10;
public string str = "Visual Programming";
};

class Program
{
static void Main(string[] args)
{
Book b = new Book();
Console.WriteLine("Book Id: "+b.a);
Console.WriteLine("Book Name: "+b.str);
Console.ReadLine();
}
}
}
Output –
Book Id: 10
Book Name: Visual Programming

Prof. Honrao Bhagyashri Prakash (8 )


Shriram Institute of Information Technology, Paniv

2) Methods –
Methods define the actions that a class can perform. Methods can take parameters that provide input
data, and can return output data through parameters. Methods can also return a value directly, without using a
parameter.
Program –
using System;
namespace Passtech
{
class sample
{
public int square(int a)
{
return a * a;
}
public void show()
{
Console.WriteLine("Welcome in Method member of class");
}
}
class Program
{

static void Main(string[] args)


{
int n,result;
Console.Write("Enter Number: ");
n = Convert.ToInt32(Console.ReadLine());
sample s = new sample();
s.show();
result = s.square(n);
Console.WriteLine("Square is: " + result);
Console.ReadLine();
}
}
}

Output –
Enter Number: 5
Welcome in Method member of class
Square is: 25

Prof. Honrao Bhagyashri Prakash (9 )


Shriram Institute of Information Technology, Paniv

Constructor -
Constructor is a special method of class, which invoked automatically whenever object of class is
created. Like methods, a constructor also contains the collection of instructions that are executed at the time of
Object creation.
An object is created on managed heap using new operator which invokes the constructor of a class.
Constructor is used for initializing object members.

Following are some features of a constructor:-

 In C#, constructor has same name as that of class.

 Constructor function automatically invoked at the time of object creation.

 It can be overloaded.

 It is called only once in the lifetime of the object that is to initialize its members.

 It does not have any return type not even void.

 Constructor need to public otherwise if private, object instantiation is not allowed.

 The constructor that does not have parameters such constructor are called default constructor.

 The constructor accept parameter these such constructor are called parameterized constructor.

Syntax –
class class_name
{
public class_name()
{
// Constructor body definition
}
}
Note -

If, we do not define a default constructor in a class, an implicit default constructor is automatically
created by the compiler.

Example –
using System;
namespace Constructor
{
class sample

Prof. Honrao Bhagyashri Prakash (10 )


Shriram Institute of Information Technology, Paniv

{
public sample()
{
Console.WriteLine("Welcome in Constructor");
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
Console.ReadLine();
}
}
}

Output –
Welcome in Constructor

 Types of Constructor -
C# provide following types of constructors.
1) Default constructor
2) Parameterized Constructor
3) Copy Constructor.
4) Static constructor
5) Private constructor.

1) Default Constructor -
A constructor with no parameters is called a default constructor. A default constructor has every
instance of the class to be initialized to the same values. If, we do not define a default constructor in a
class, an implicit default constructor is automatically created by the compiler.
Syntax -

Prof. Honrao Bhagyashri Prakash (11 )


Shriram Institute of Information Technology, Paniv

class class_name
{
public class_name()
{
// Constructor body definition
}
}
Example –
using System;
namespace Constructor
{
class sample
{
public sample()
{
Console.WriteLine("Welcome in Constructor");
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
Console.ReadLine();
}
}
}
Output –
Welcome

2) Parameterized constructor –
A constructor having at least one parameter is called as parameterized constructor. The
advantage of a parameterized constructor is that you can initialize each instance of the class with a
different value.

Prof. Honrao Bhagyashri Prakash (12 )


Shriram Institute of Information Technology, Paniv

Syntax –
class class_name
{
public class_name(parameter list)
{
// Constructor body definition
}
}
Example –
using System;
namespace Constructor
{
class sample
{
public sample(int a)
{
Console.WriteLine("Square is: "+a*a);
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample(5);
sample s1 = new sample(2);
Console.ReadLine();
}
}
}

Output –
Square is: 25
Square is: 4

Prof. Honrao Bhagyashri Prakash (13 )


Shriram Institute of Information Technology, Paniv

3) Copy Constructor –
The constructor which creates an object by copying variables from another object is called a
copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an
existing instance.
Syntax –
class class_name
{
public class_name(class_name object)
{
// Constructor body definition
}
}
Example –
using System;
namespace Constructor
{
class Student
{
public string name, location;
public Student(string a, string b)
{
name = a;
location = b;
}
public Student (Student s)
{
name = s.name;
location = s.location;
}
}
class Program
{
static void Main(string[] args)

Prof. Honrao Bhagyashri Prakash (14 )


Shriram Institute of Information Technology, Paniv

{
Student std1 = new Student("Bhushan", "Malshiras");
Student std2 = new Student(std1);
std2.name="Amit";
std2.location="Pune";
Console.WriteLine(std1.name + ", " + std1.location);
Console.WriteLine(std2.name + ", " + std2.location);
Console.ReadLine();
}
}
}

Output –
Bhushan, Malshiras
Amit, Pune

4) Static Constructor –
In c#, Static Constructor is useful to perform a particular action only once throughout the
application. If we declare a constructor as static, then it will be invoked only once irrespective of the
number of class instances and it will be called automatically before the first instance is created.
Generally, in c# the static constructor will not accept any access modifiers and parameters. In simple
words, we can say it‟s parameterless.
The following are the properties of static constructor in c# programming language.
a. Static constructor in c# won‟t accept any parameters and access modifiers.
b. The static constructor will invoke automatically, whenever we create the first instance of a class.
c. The static constructor will be invoked by CLR so we don‟t have a control on static constructor
execution order in c#.
d. In c#, only one static constructor is allowed to create.
Syntax –
class class_name
{
static class_name()
{
// Constructor body definition
}
}

Prof. Honrao Bhagyashri Prakash (15 )


Shriram Institute of Information Technology, Paniv

Example -
using System;
namespace Constructor
{
class Sample
{
static Sample()
{
Console.WriteLine("Hi, Static constructor");
}
public Sample()
{
Console.WriteLine("Hi, Default constructor");
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Sample s1 = new Sample();
Console.ReadLine();
}
}
}
Output -
Hi, Static constructor
Hi, Default constructor
Hi, Default constructor

5) Private Constructor –
A private constructor is a special instance constructor. It is generally used in classes that contain
static members only. If a class has one or more private constructors and no public constructors, other
classes (except nested classes) cannot create instances of this class. The use of private constructor is to

Prof. Honrao Bhagyashri Prakash (16 )


Shriram Institute of Information Technology, Paniv

serve singleton classes. A singleton class is one which limits the number of objects created to one. Using
private constructor we can ensure that no more than one object can be created at a time
1) One use of private constructor is when we have the only static member.
2) It provides the implementation of singleton class pattern.
3) Once we provide constructor (private/public/any) the compiler will not add the no parameter public
constructor to any class.
Syntax -
class class_name
{
private class_name()
{
}
}
Example-
using System;
namespace Constructor
{
class Sample
{
private Sample()
{
Console.WriteLine("Hi, Welcome in Private Contructor");
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Console.ReadLine();
}
}
}
Output –
Here, generate exception Error 'Constructor.Sample.Sample()' is inaccessible due to its
protection level.

Prof. Honrao Bhagyashri Prakash (17 )


Shriram Institute of Information Technology, Paniv

OR
Example-
using System;
namespace Constructor
{
class Sample
{
public static string name;

public Sample(string n)
{
name = n;
}
private Sample()
{
Console.WriteLine("Hi, Welcome in Private Contructor");
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample("Amit");
Console.WriteLine("User Name: " + Sample.name);
Console.ReadLine();
}
}
}

Output –
User Name: Amit

Prof. Honrao Bhagyashri Prakash (18 )


Shriram Institute of Information Technology, Paniv

Destructor -
In c#, Destructor is a special method of a class and it is used in a class to destroy the object or instances
of classes. The destructor in c# will invoke automatically whenever the class instances become unreachable .
The destructor is work apposite of constructor.
Following are the properties of destructor in c# programming language.
1) In c#, destructors can be used only in classes and a class can contain only one destructor.
2) The destructor in class can be represented by using tilde (~) operator
3) The destructor in c# won‟t accept any parameters and access modifiers.
4) The destructor will invoke automatically, whenever an instance of a class is no longer needed.
5) The destructor automatically invoked by garbage collector whenever the class objects that are no longer
needed in the application.
Syntax –
class class_name
{
~ class_name()
{
}
}
Example –
using System;
namespace Constructor
{
class Sample
{
public Sample()
{
Console.WriteLine("Hi, Welcome in Contructor");
}
~Sample()
{
Console.WriteLine("Hi, Welcome in Destructor");
}
}
class Program
{
static void Main(string[] args)

Prof. Honrao Bhagyashri Prakash (19 )


Shriram Institute of Information Technology, Paniv

{
Sample s = new Sample();
Console.ReadLine();
}
}
}

Output –
Hi, Welcome in Constructor

Method Overloading -
Creating a multiple methods in a class with same name but different parameters and types is called as
method overloading. We can have multiple definitions for the same function name in the same scope. We
cannot overload function declarations that differ only by return type. Method overloading is the example of
Compile time polymorphism which is done at compile time.

 Method overloading can be achieved by using following things :

 By changing the number of parameters used.

 By changing the order of parameters.

 By using different data types for the parameters.

Example -

using System;
namespace MethodOverloading
{
class sample
{
public void show(int a, int b)
{
int c = a + b;
Console.WriteLine("Addition of integer is: " + c);
}
public void show(float n, float m)
{
float r = n + m;

Prof. Honrao Bhagyashri Prakash (20 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("Addition of float is: " + r);


}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
s.show(10, 20);
s.show(5.20f, 10.25f);
Console.ReadLine();
}
}
}

Output -
Addition of integer is: 30
Addition of float is: 15.45

Properties -
 Properties are special member of a class provides an easy way to read or write the value of private data
member.
 Fields are data member of a class. Properties are extension to field & can be accessed using the same
syntax.
 Fields are by default private and hence inaccessible outside the class.
 Some or all of these data member can be accessed from outside the class with the help of special method
called properties. So poperties are also called as „smart field‟.
 Unlike fields, properties do not denote storage location. Instead, properties have accessors that specify
the statements to be executed when their values are read or written.
Syntax –

public propertyType propertyName

get

Prof. Honrao Bhagyashri Prakash (21 )


Shriram Institute of Information Technology, Paniv

return fieldname;

set

fieldname = value;

}
Where,
 Properties has two access specifier
a) get: - The get accessors retrives data member values.

b) set: - The set accessors sets the value of a property and is similar to a method that return void. The
set accessor automatically receives a parameter called value, that contains the value being assigned
to the property.
Example –

using System;
namespace readonlyExample
{
class smaple
{
private int num;

public int Anum


{
get
{
return num;
}
set
{
if (num >= 0)
{
num = value;
}
}
}
}
class Program
{
static void Main(string[] args)
{
smaple s = new smaple();
s.Anum = 100;

Prof. Honrao Bhagyashri Prakash (22 )


Shriram Institute of Information Technology, Paniv

int a = s.Anum;
Console.WriteLine("Value is: "+a);
Console.ReadLine();
}
}
}

Output –

Value is: 100

 Features of properties:-

1. Property do not have same name as that of underlying data member.

2. If only get is specified, then the property becomes a read only property.

3. If only set is specified, then the property becomes a write only property.

4. If both are specified, then the property is read/write property.

5. Property are not variable and therefore can‟t be passed as ref & out parameter.

6. Properties can be static or instance property.

Local Variable –

A local variable is used where the scope of the variable is within the method in which it is
declared. They can be used only by statements that are inside that function or block of code.
Example: -
using System;
public class Program
{
public static void Main(string [] args)
{
int a;
a = 100;
// local variable
Console.WriteLine("Value:"+a);
}
}

Output: -
Value: 100

Prof. Honrao Bhagyashri Prakash (23 )


Shriram Institute of Information Technology, Paniv

Static class:-
In C#, one is allowed to create a static class, by using static keyword. A static class
can only contain static data members and static methods. It is not allowed to create objects of

the static class and since it does not allow to create objects it means it does not allow instance

constructor. Static classes are sealed, means you cannot inherit a static class from another

class.

Syntax:
static class Class_Name

// static data members

// static method

In C#, the static class contains two types of static members as follows:

1) Static Data Members


2) Static Methods

1) Static Data Members:


As static class always contains static data members, so static data members are
declared using static keyword and they are directly accessed by using the class name. The memory
of static data members is allocating individually without any relation with the object.
Syntax:
static class Class_name
{

public static nameofdatamember;

2) Static Methods:
As static class always contains static methods, so static methods are

declared using static keyword. These methods only access static data members, they can not

access non-static data members.

Syntax:
static class Class_name

Prof. Honrao Bhagyashri Prakash (24 )


Shriram Institute of Information Technology, Paniv

public static nameofmethod()

// code

Program:-
// C# program to illustrate the

// concept of static class

using System;

namespace ExampleOfStaticClass
{

// Creating static class

// Using static keyword

static class Author

// Static data members of Author

public static string A_name = “Bhushan”;

public static string L_name = “CSharp”;

public static int T_no = 84;


// Static method of Author

public static void details()

Console.WriteLine(“The details of Author is:”);

// Driver Class

public class GFG

// Main Method

static public void Main()

Prof. Honrao Bhagyashri Prakash (25 )


Shriram Institute of Information Technology, Paniv

// Calling static method of Author

Author.details();
// Accessing the static data members of Author

Console.WriteLine(“Author name : {0}”, Author.A_name);

Console.WriteLine(“Language : {0}”, Author.L_name);

Console.WriteLine(“Total number of articles : {0}”,Author.T_no);

Console.Read();

}
}

Output:-
The details of Author is:

Author name : Bhushan

Language : CSharp

Total number of articles : 84

Difference between Static class and Non-Static class-


Sr.
Static Class Non-Static Class
No.
Non-Static class is not defined by using static
1 Static class is defined using static keyword.
keyword.
In static class, you are not allowed to create In non-static class, you are allowed to create
2
objects. objects using new keyword.
The data members of static class can be The data members of non-static class is not
3
directly accessed by its class name. directly accessed by its class name.
Non-static class may contain both static and
4 Static class always contains static members.
non-static methods.
Static class does not contain an instance Non-static class contains an instance
5
constructor. constructor.
Static class cannot inherit from another Non-static class can be inherited from another
6
class. class.

Prof. Honrao Bhagyashri Prakash (26 )


Shriram Institute of Information Technology, Paniv

Nested Class –
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class
combines the fields and methods (member function which defines actions) into a single unit. In C#, a user is
allowed to define a class within another class. Such types of classes are known as nested class.
A nested class is a class declared in another enclosing class. It is a member of its enclosing class
and the members of an enclosing class have no access to members of a nested class.
Syntax:
class Outer_class
{
// Code..
class Inner_class
{
// Code..
}
}

Program :-
using System;
public class Outer_class
{
public void method1()
{
Console.WriteLine("Outer class method");
}
public class Inner_class
{
public void method2()
{
Console.WriteLine("Inner class Method");
}
}
}
public class GFG
{
static public void Main(string [] args)
{
Outer_class obj1 = new Outer_class();
obj1.method1();
Outer_class.Inner_class obj2 = new Outer_class.Inner_class();
obj2.method2();
Console.Read();

Prof. Honrao Bhagyashri Prakash (27 )


Shriram Institute of Information Technology, Paniv

}
}

Output:-
Outer class method
Inner class Method

Indexer –
 Indexer are location indicator and are used to access class objects, just like accessing elements in an
array. They are usefull in cases where a class is a container for other objects.
 Indexers takes an index arguments and looks like an array.
 Indexers are declared using the name this.
 The indexers are usually known as „smart array‟.
 Defining C# indexer is much like defining a properties, except that their accessors take parameters.
 We can say that an indexer is a member that enables an object to be indexed in the same way as an
array.
 Indexers have two accessors:-
a) get:-
The get accessor retives array elements of specified index position.
b) set:-
The set accessor sets the value at specified index position in an array.
 Indexers are instance member of a class.
 Indexers are never static in C#.
 One class can hve only one indexer.
 The return type can be any valid C# types.
 Indexer in C# must have at least one parameter, else the compiler will generate a compilation error.
 Indexer allow us to use a class as an array and enable an object to access the array elements of class.

Syntax:-
Public type this [int index]
{
get
{
Return collection_name [index];
}
Set
{
Collection_name [index] = value;

Prof. Honrao Bhagyashri Prakash (28 )


Shriram Institute of Information Technology, Paniv

}
}

The this keyword shows that, the object is of the current class.
Example –
using System;
namespace EgIndexer
{
class Sample
{
private string[] str=new string[3];

public string this[int index]


{
get
{
return str[index];
}
set
{
str[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
s[0] = "CPP";
s[1] = "DS";
s[2] = "VP";
Console.WriteLine("String are: ");
Console.WriteLine(s[0]);
Console.WriteLine(s[1]);
Console.WriteLine(s[2]);
Console.ReadLine();
}
}
}
Output -
String are:

CPP

DS

VP

Prof. Honrao Bhagyashri Prakash (29 )


Shriram Institute of Information Technology, Paniv

Comparison of Indexer and Properties –

Properties Indexer

1. Properties are declared by giving a unique name. Indexers are declared without giving a name.

2. Properties are identified by the names While indexers are identified by the signatures.

Properties can be declared as a static or an Indexers are always declared as instance member,
3.
instance member. never as static member.

Properties are invoked through a described Indexers are invoked using an index of the created
4.
name. object.

A property does not needs this keyword in their


5. Indexers need this keyword in their keyword.
creation.
A get accessor of a property does not have any A get accessor of a property contains the list of same
6.
parameters. proper parameters as indexers.
A set accessor of an indexer has the same formal
A set accessor of a property contains the
7. parameter list as the indexer, in addition to the
implicit value parameter
value parameter.

Inheritance –
“Inheritance is a mechanism of creating new classes from an existing class”. Or in other word
“The mechanism of creating derived classes from existing base class is called as inheritance”.
The old class or existing class is known as base class or parent class or super
class. The newly created class is called as derived class or child class or sub class. The main purpose of
inheritance is reusability of code. C# classes can be reused in several ways. Reusability is achieved by
designing new classes reusing all or some of the properties of existing classes.
A derived class is s completely new class that incorporates all the data and methods of its base
class. It can also have its own data and methods members that are unique to itself.

Class A Base class

Class B Derived class

Prof. Honrao Bhagyashri Prakash (30 )


Shriram Institute of Information Technology, Paniv

Syntax –
Access_modifier class classname
{
// body of class
}
Access_modifier class derived class : base class
{
// body of derived class
}

In C# we use the colon (:) operator to inherit that a class from another class (known as base
class). Means colon signifies that the properties of the base class are extended to the derived class. The derived
class inherits some or all of the traits from base class.
 Types of Inheritance -
C# support 3 types of inheritance these are –
1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
Note - C# does not directly support to multiple inheritance. However this concept is implemented using
interfaces.
1) Single Inheritance –
Single inheritance means to create a new class (derived class) from an existing only one
class(base class).

Base Class

Derived Class

Syntax –

Access modifier class class name

// body of class

Prof. Honrao Bhagyashri Prakash (31 )


Shriram Institute of Information Technology, Paniv

Access modifier class derived class : base class

// body of derived class

Example –
using System;
namespace Inheritance
{
class Square
{
public int a;
public void getinfo(int n)
{
a = n;
}
}
class SquareResult : Square
{
public int result()
{
return a * a;
}
}
class Program
{
static void Main(string[] args)
{
int num;
Console.Write("Enter Number: ");
num = Convert.ToInt32(Console.ReadLine());
SquareResult s = new SquareResult();
s.getinfo(num);

Prof. Honrao Bhagyashri Prakash (32 )


Shriram Institute of Information Technology, Paniv

int r = s.result();
Console.WriteLine("Square is: " + r);
Console.ReadLine();
}
}
}

Output –
Enter Number: 5
Square is: 25

2) Multilevel Inheritance –
The multilevel inheritance means new class is created from another derived class or existing
class. In the other word we can say that derived class is created from another derived class is known as
multilevel inheritance.

A Base Class

B Inheritance base class(Intermediate Class)

C Derived class

The class A serves as a base class for derived class B which turn serves as a base class for the
derived class C.
Syntax –
class A
{
----
}
class B : A
{
----
}
class C : B
{

Prof. Honrao Bhagyashri Prakash (33 )


Shriram Institute of Information Technology, Paniv

----
}

Example –

using System;
namespace Inheritance
{
class ClassA
{
public void MethodA()
{
Console.WriteLine("Welcome in A class");
}
}
class ClassB : ClassA
{
public void MethodB()
{
Console.WriteLine("Welcome in B class");
}
}
class ClassC : ClassB
{
public void MethodC()
{
Console.WriteLine("Welcome in C class");
}
}
class Program
{
static void Main(string[] args)
{
ClassC c = new ClassC();
c.MethodA();

Prof. Honrao Bhagyashri Prakash (34 )


Shriram Institute of Information Technology, Paniv

c.MethodB();
c.MethodC();
Console.ReadLine();
}
}
}

Output –
Welcome in A class
Welcome in B class
Welcome in C class

3) Hierarchical Inheritance –
The properties of one class may be inherited by more than one class this process in known as
hierarchical inheritance. In the hierarchical inheritance more than on derived class is created from a
single base class.

Base Class

Derived Class Derived Class

Syntax –
class A
{
----
}
class B : A
{
----
}
class C : A
{
----
}

Prof. Honrao Bhagyashri Prakash (35 )


Shriram Institute of Information Technology, Paniv

Example –
using System;
namespace Inheritance
{
class ClassA
{
public void MethodA()
{
Console.WriteLine("Welcome in A class");
}
}
class ClassB : ClassA
{
public void MethodB()
{
Console.WriteLine("Welcome in B class");
}
}
class ClassC : ClassA
{
public void MethodC()
{
Console.WriteLine("Welcome in C class");
}
}
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
b.MethodA();
b.MethodB();
ClassC c = new ClassC();
c.MethodA();
c.MethodC();

Prof. Honrao Bhagyashri Prakash (36 )


Shriram Institute of Information Technology, Paniv

Console.ReadLine();
}
}
}
Output –
Welcome in A class
Welcome in B class
Welcome in A class
Welcome in C class

Abstract class –
Abstract class is a special class that cannot be instantiated. It means abstract class is a restricted
class that cannot be used to create object.
The purpose of an abstract class is to provide a blueprint for derived classes and set some rules
what the derived classes must implement when they inherit an abstract class. We can use an abstract class as a
base class and all derived classes must implement abstract definitions. An abstract class can contain either
abstract methods or non-abstract method. Abstract member do not have any implementation in the abstract
class, but the same has to be provided in its derived class. When a method is declared as abstract in the base
class then every derived class of that class must provide its own definition for that method. An abstract method
must be implemented in all non-abstract classes using the override keyword. After overriding the abstract
method is in the non-Abstract class.

When a class contains at least one abstract method, then the class must be declared as abstract class.
Example –
using System;
namespace Inheritance
{
abstract class sample
{
public abstract void msg();
public void show()
{
Console.WriteLine("Welcome");
}
}

Prof. Honrao Bhagyashri Prakash (37 )


Shriram Institute of Information Technology, Paniv

class demo : sample


{
public override void msg()
{
Console.WriteLine("Abstract class has abstract method");
}
public void display()
{
Console.WriteLine("Thank You");
}
}
class Program
{
static void Main(string[] args)
{
demo d = new demo();
d.show();
d.display();
d.msg();
Console.ReadLine();
}
}
}
Output –
Welcome
Thank You
Abstract class has abstract method

 Features of Abstract Class:-


1) An abstract class cannot be instantiated.
2) An abstract class contains abstract members as well as non- abstract members.
3) An abstract class cannot be sealed class because the sealed modifier prevents a class from being
inherited and the abstract modifier requires a class to be inherited.

Prof. Honrao Bhagyashri Prakash (38 )


Shriram Institute of Information Technology, Paniv

4) A non- abstract class which is derived from an abstract class must include actual implementations of all
the abstract members of the parent abstract class.
5) An abstract class can be inherited from a class and one or more interfaces.
6) An abstract class can has access modifiers like private, protected, internal with class members. But
abstract members cannot have private access modifier.
7) An Abstract class can has instance variables (like constants and fields)
8) An abstract class can has constructors and destructor.
9) An abstract method is implicitly a virtual method.
10) Abstract properties behave like abstract methods.
11) An abstract class cannot be inherited by structures.
12) An abstract class cannot support multiple inheritances.

Abstract Method (function) –


Abstract Method is a method without method body. An abstract is written when the same method
has to perform different tasks depending on the object calling it. Besides making a class abstract by using
abstract keyword, we can also create abstract methods.
An abstract method has no implementation, and its implementation is left to the classes that inherit from
the class that defines it.
An abstract method is implicitly a virtual method and does not provide any implementation. Method
body simply consists of a semicolon.
Syntax:–
public abstract void Draw (int x, int y);
Example -
using System;
namespace Inheritance
{
abstract class Myclass
{
public abstract void cal(int n);
}
class Sample:Myclass
{
public override void cal(int n)
{

Prof. Honrao Bhagyashri Prakash (39 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("Square is: " + n * n);


}
}
class Demo : Myclass
{
public override void cal(int n)
{
Console.WriteLine("Cube is: " + n * n * n);
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
s.cal(2);
Demo d = new Demo();
d.cal(5);
Console.ReadLine();
}
}
}

Output –
Square is: 4
Cube is: 125

 Characteristics of abstract methods are:-


1) It cannot have implementation in its declaration class.
2) Its implementation must provide in non-abstract derived classes by overriding the method.
3) These methods can be declared only in abstract classes.
4) It cannot take either static or virtual modifiers.

Prof. Honrao Bhagyashri Prakash (40 )


Shriram Institute of Information Technology, Paniv

Sealed class –
To avoid inheritance we use sealed keyword before the class declaration. Inheritance is restricted using
sealed keyword in C#. Structures are implicitly sealed therefore, they cannot be inherited.
Syntax:-
sealed class classname
{
-------
}
 Rules of sealed class:-
a. When we use sealed keyword within class declaration then we cannot inherit this class.
b. Sealed class cannot contain virtual methods.
c. Sealed class also can not contain abstract methods.

Example –
using System;
namespace abc
{
sealed class A
{
public int a = 10;
public void display()
{
Console.WriteLine("a: " + a);
}
} // The following class is illegal
class B : A // Error ! can‟t derive class A
{
public void put()
{
Console.WriteLine("a: " + a);
}
}
class program
{
public static void Main()
{
B b = new B();
b.display();
b.put();
Console.Read();

Prof. Honrao Bhagyashri Prakash (41 )


Shriram Institute of Information Technology, Paniv

}
}
}

It is illegal for B to inherit A, because A is declared as sealed .

Sealed Method –
We can use seal method so that other derived classes cannot override the implementation that we have
provided in the current class.
Use of the sealed modifier prevents a derived class from further overriding the method.
Example -
using System;
namespace Inheritance
{
class xyz
{
public virtual void display()
{
Console.WriteLine("Within xyz class");
}
}
class abc : xyz
{
sealed public override void display()
{
// here we override diplay method
Console.WriteLine("Within abc class");
}
}
class opq : abc
{
public override void display()
{
// cannot allowed here override because
// we seal display method within abc

Prof. Honrao Bhagyashri Prakash (42 )


Shriram Institute of Information Technology, Paniv

// class so we cannot override again


// in opq class
}
}
class program
{
public static void Main()
{
opq o = new opq();
o.display();
Console.Read();
}
}
}

In above example we override display () method within abc class. We use sealed keyword within abc
class display method for to avoid further overridden.
In a opq class, if we try to override display () method again then the error displayed, because we seal this
method within abc class.

Interface –
C# does not support multiple inheritances. That is classes in C# cannot have more than one base
class. C# provides alternate approach known as interface. Interface is reference type defined in CLR. Interface
is like a class, but it can only declare methods and properties, it does not implement these in an interfaces. We
implement these method in a class those whose implement these interface. Following are some point about
interface.

1. All members of an interface are implicitly public and abstract.

2. An interface cannot contain constant field, constructor & destructors.

3. It‟s member cannot be declared static.

4. Since the methods in an interface are abstract, they do not include implementation code.

5. An interface can inherit multiple interfaces.

Prof. Honrao Bhagyashri Prakash (43 )


Shriram Institute of Information Technology, Paniv

 Defining interface –
An Interface can contain one or more methods, Properties, Indexers & events, but none of them are
implemented in the interface itself. It is the responsibility of the class that implements the interface to define the
code for implementation of these members.

Syntax of an interface definition is interface:


interface interface_name
{
Member declaration
}

Here interface is the keyword and interface_name is a valid identifier. Member declaration will
contain only a list of members without implementation code.
interface addition
{
int add ( );
}

 Implementing Interface :-
Interfaces are used as “Super class”, whose properties are inherited by classes. It is therefore necessary
to create a class that inherits the given interface. This is done as follows:
class classname : interfacename
{
Body of Class;
}

Here the class classname implements the interface interfacename.


The following statement shows that a class can extends another class while implementing interface.
class classname : superclass, interface1, interface2
{
Body of class
}
Example -
using System;

Prof. Honrao Bhagyashri Prakash (44 )


Shriram Institute of Information Technology, Paniv

namespace Constructor
{
interface sample
{
int add();
}
class Demo : sample
{
public int a, b;
public Demo(int n1, int n2)
{
a = n1;
b = n2;
}
public int add()
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
int x, y;
Console.Write("Enter first number: ");
x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
y = Convert.ToInt32(Console.ReadLine());
Demo d = new Demo(x, y);
int result=d.add();
Console.WriteLine("Addition is: " + result);
Console.ReadLine();
}
}
}

Prof. Honrao Bhagyashri Prakash (45 )


Shriram Institute of Information Technology, Paniv

Output –
Enter first number: 2
Enter second number: 5
Addition is: 7

Polymorphism -
Polymorphism means having many forms. Polymorphism is ability of a message to be displayed in
more than one form. In object-oriented programming paradigm, polymorphism is often expressed as 'one
interface, multiple functions'.
Example – a person at a same time can have different characteristic like a man at a same time is father,
husband, a employee, so person possess different behavior in different situation this called polymorphism.
The polymorphism is divided into two types.
1) Static polymorphism.
2) Dynamic polymorphism.

1) Static polymorphism –
The mechanism of linking a function with an object during compile time is called early binding. It is
also called static binding. C# provides two techniques to implement static polymorphism. They are:
a) Method overloading
b) Operator overloading
2) Dynamic Polymorphism –
The mechanism of linking a function with an object during runtime is called late binding. It is
also called dynamic binding. The late binding is implement through virtual function.

a) Method Overloading -
Creating a multiple methods in a class with same name but different parameters and types is called as
method overloading. We can have multiple definitions for the same function name in the same scope. We
cannot overload function declarations that differ only by return type. Method overloading is the example of
Compile time polymorphism which is done at compile time.

 Method overloading can be achieved by using following things :

 By changing the number of parameters used.

 By changing the order of parameters.

 By using different data types for the parameters.

Prof. Honrao Bhagyashri Prakash (46 )


Shriram Institute of Information Technology, Paniv

Example -

using System;
namespace MethodOverloading
{
class sample
{
public void show(int a, int b)
{
int c = a + b;
Console.WriteLine("Addition of integer is: " + c);
}
public void show(float n, float m)
{
float r = n + m;
Console.WriteLine("Addition of float is: " + r);
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
s.show(10, 20);
s.show(5.20f, 10.25f);
Console.ReadLine();
}
}
}

Output -
Addition of integer is: 30
Addition of float is: 15.45

Prof. Honrao Bhagyashri Prakash (47 )


Shriram Institute of Information Technology, Paniv

b) Operator Overloading –
The concept of overloading a function can also be applied to operators. Operator overloading gives the
ability to use the same operator to do various operations. It provides additional capabilities to C# operators
when they are applied to user-defined data types. It enables to make user-defined implementations of various
operations where one or both of the operands are of a user-defined class. Only the predefined set of C#
operators can be overloaded. Operator overloading is basically the mechanism of providing a special meaning to
an C# operator. Overloaded operators are functions with special names the keyword "operator" followed by the
symbol for the operator being defined.
Syntax -
access specifier className operator Operator_symbol (parameters)
{
// Code
}

Types of operator overloading –


1) Unary Operator overloading
2) Binary Operator overloading

1) Unary Operator overloading –


Unary operator overloading work on only one operator. Unary operators are +, -, !, ~, ++, – –
Example -
using System;
namespace Inheritance
{
class sample
{
public int num1, num2;
public sample(int n1, int n2)
{
num1 = n1;
num2 = n2;
}
public static sample operator -(sample s)
{
s.num1 = -s.num1;

Prof. Honrao Bhagyashri Prakash (48 )


Shriram Institute of Information Technology, Paniv

s.num2 = -s.num2;
return s;
}
public void display()
{
Console.WriteLine("Number 1 is: " + num1);
Console.WriteLine("Number 2 is: " + num2);
}
}
class program
{
public static void Main()
{
sample s1 = new sample(10, -20);
s1 = -s1;
s1.display();
Console.ReadLine();
}
}
}

Output –
Number 1 is: -10
Number 2 is: 20

2) Binary Operator –
Binary Operators will work with two Operands. Examples of binary operators include the
Arithmetic Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+, %=) Relational
Operators etc. Overloading a binary operator is similar to overloading a unary operator, except that a -
binary operator requires an additional parameter.
Example –
using System;
namespace Constructor
{
class sample

Prof. Honrao Bhagyashri Prakash (49 )


Shriram Institute of Information Technology, Paniv

{
public int num;
public sample()
{
}
public sample(int n)
{
num = n;
}
public static sample operator +(sample s1,sample s2)
{
sample s3=new sample();
s3.num=s2.num+s1.num;
return s3;
}
public void display()
{
Console.WriteLine("Number is: " + num);
}
}
class Program
{
static void Main(string[] args)
{
sample sam1 = new sample(20);
sample sam2 = new sample(30);
sample sam3 = new sample();
sam3 = sam1 + sam2;
sam1.display();
sam2.display();
sam3.display();
Console.ReadLine();
}
}
}

Prof. Honrao Bhagyashri Prakash (50 )


Shriram Institute of Information Technology, Paniv

Output –
Number is: 20
Number is: 30
Number is: 50

 Virtual Methods –
The virtual keyword is useful in modifying a method, property, indexer, or event. When you
have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual
functions. The virtual functions could be implemented differently in different inherited class and the call to
these functions will be decided at runtime.
The following is a virtual function
public virtual int area()
{

}
Program :-
using System;
namespace Inheritance
{
public class sample
{
public virtual void show()
{
}

}
class sample2 : sample
{
public override void show()
{
Console.WriteLine("Welcome....");
}
}
class Program
{
static void Main(string[] args)
{
sample2 s2 = new sample2();
s2.show();
Console.ReadLine();
}

Prof. Honrao Bhagyashri Prakash (51 )


Shriram Institute of Information Technology, Paniv

}
}
Output :-
Welcome….

 Method Overriding –
If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific
implementation of the method which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.
Program –
using System;
public class Animal
{
public virtual void eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding
{
public static void Main()
{
Dog d = new Dog();
d.eat();
Console.ReadLine();
}
}

Output –
Eating bread...

Prof. Honrao Bhagyashri Prakash (52 )


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 Bhagyashri Prakash (53 )


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

Prof. Honrao Bhagyashri Prakash (54 )


Shriram Institute of Information Technology, Paniv

m = Convert.ToInt32(Console.ReadLine());
Program p = new Program();
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;

Prof. Honrao Bhagyashri Prakash (55 )


Shriram Institute of Information Technology, Paniv

b = 200;
Console.WriteLine("a: " + a);
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.

Prof. Honrao Bhagyashri Prakash (56 )


Shriram Institute of Information Technology, Paniv

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

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 Bhagyashri Prakash (57 )

You might also like