Unit 2 - DOT - NET - CORE
Unit 2 - DOT - NET - CORE
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.
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";
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.
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
{
}
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");
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;
OR
class_name object_name = new class_name ();
Rectangle
Object
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.
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.
Syntax:
objectname.variablename;
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:-
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();
}
}
}
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
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
{
Output –
Enter Number: 5
Welcome in Method member of class
Square is: 25
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.
It can be overloaded.
It is called only once in the lifetime of the object that is to initialize its members.
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
{
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 -
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.
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
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)
{
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
}
}
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
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.
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
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)
{
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.
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;
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 –
get
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;
int a = s.Anum;
Console.WriteLine("Value is: "+a);
Console.ReadLine();
}
}
}
Output –
Features of properties:-
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.
5. Property are not variable and therefore can‟t be passed as ref & out parameter.
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
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 method
In C#, the static class contains two types of static members as follows:
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
Syntax:
static class Class_name
// code
Program:-
// C# program to illustrate the
using System;
namespace ExampleOfStaticClass
{
// Driver Class
// Main Method
Author.details();
// Accessing the static data members of Author
Console.Read();
}
}
Output:-
The details of Author is:
Language : CSharp
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();
}
}
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;
}
}
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];
CPP
DS
VP
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.
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.
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 –
// body of 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);
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
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
{
----
}
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();
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
Syntax –
class A
{
----
}
class B : A
{
----
}
class C : A
{
----
}
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();
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");
}
}
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.
Output –
Square is: 4
Cube is: 125
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();
}
}
}
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
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.
4. Since the methods in an interface are abstract, they do not include implementation code.
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.
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;
}
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();
}
}
}
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.
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
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
}
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
{
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();
}
}
}
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();
}
}
}
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...
}
}
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();
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);
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
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.
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