0% found this document useful (0 votes)
29 views62 pages

C# Notes

The document provides an overview of control statements in C#, including looping statements (for, while, do-while) and conditional statements (if, if-else, switch). It also covers the concept of methods, including their declaration, parameters, and return types, along with examples. Additionally, it discusses classes and objects in C#, focusing on encapsulation, inheritance, polymorphism, and access modifiers.

Uploaded by

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

C# Notes

The document provides an overview of control statements in C#, including looping statements (for, while, do-while) and conditional statements (if, if-else, switch). It also covers the concept of methods, including their declaration, parameters, and return types, along with examples. Additionally, it discusses classes and objects in C#, focusing on encapsulation, inheritance, polymorphism, and access modifiers.

Uploaded by

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

CONCEPT 1: Control Statement

1.1 Looping Statement


1.1.1 C# For Loop
The C# for loop is used to iterate a part of the program several times. If the
number of iterations is fixed, it is recommended to use for loop than while or
do-while loops.

The C# for loop is same as C/C++. We can initialize variable, check condition
and increment/decrement value.

Syntax:

for(initialization; condition; incr/decr){


//code to be executed
}

Example 1:
using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
Console.WriteLine(i);
}
}
}

Example 2:
using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
Console.WriteLine(i+" "+j);
}
}
}
}

Example 3: Infinite Loop


using System;
public class ForExample
{
public static void Main(string[] args)
{
for (; ;)
{
Console.WriteLine("Infinitive For Loop");
}
}
}

1.1.2 C# While Loop


In C#, while loop is used to iterate a part of the program several times. If the
number of iterations is not fixed, it is recommended to use while loop than
for loop.

Syntax:

while(condition){
//code to be executed
}
Example 1
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=10)
{
Console.WriteLine(i);
i++;
}
}
}

Example 2
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
Console.WriteLine(i+" "+j);
j++;
}
i++;
}
}
}

Example 3
using System;
public class WhileExample
{
public static void Main(string[] args)
{
while(true)
{
Console.WriteLine("Infinitive While Loop");
}
}
}

1.1.3 C# Do…While Loop


The C# do-while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed and you must have to execute the loop at
least once, it is recommended to use do-while loop.

The C# do-while loop is executed at least once because condition is checked


after loop body.

Syntax:

do{
//code to be executed
}while(condition);

Example 1:
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i=1;

do{
int j = 1;

do{
Console.WriteLine(i+" "+j);
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}
}

1.2 Conditional Statements


In C# programming, the if statement is used to test the condition. There are various
types of if statements in C#.
 if statement
 if-else statement
 nested if statement
 if-else-if ladder

1.2.1 C# if statement
The C# if statement tests the condition. It is executed if condition is true.

Syntax:

if(condition){
//code to be executed
}

Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}

}
}

1.2.2 C# if-else statement


The C# if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.

Syntax:

if(condition){
//code if condition is true
}else{
//code if condition is false
}

Example
using System;
public class EvenOdd
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}

C# If-else Example: with input from user


In this example, we are getting input from the user using Console.ReadLine()
method. It returns string. For numeric value, you need to convert it into int
using Convert.ToInt32() method.

using System;
public class EvenOdd
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}

1.2.3 C# IF-else-if ladder Statement


The C# if-else-if ladder statement executes one condition from multiple
statements.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example 1: Grading System

using System;
public class Grading
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());

if (num <0 || num >100)


{
Console.WriteLine("wrong number");
}
else if(num >= 0 && num < 50){
Console.WriteLine("Fail");
}
else if (num >= 50 && num < 60)
{
Console.WriteLine("D Grade");
}
else if (num >= 60 && num < 70)
{
Console.WriteLine("C Grade");
}
else if (num >= 70 && num < 80)
{
Console.WriteLine("B Grade");
}
else if (num >= 80 && num < 90)
{
Console.WriteLine("A Grade");
}
else if (num >= 90 && num <= 100)
{
Console.WriteLine("A+ Grade");
}
}
}

Example 2: Finding the Greatest Number

using System;

namespace Conditional
{
class Nested
{
public static void Main(string[] args)
{
int first = 7, second = -23, third = 13;
if (first > second)
{
if (firstNumber > third)
{
Console.WriteLine("{0} is the largest", first);
}
else
{
Console.WriteLine("{0} is the largest", third);
}
}
else
{
if (second > third)
{
Console.WriteLine("{0} is the largest",
second);
}
else
{
Console.WriteLine("{0} is the largest", third);
}
}
}
}
}

1.2.4 C# Switch Statement


The C# switch statement executes one statement from multiple conditions. It
is like if-else-if ladder statement in C#.

Syntax:

switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......

default:
//code to be executed if all cases are not matched;
break;
}
Example 1:
using System;
public class SwitchExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
}

Example 2:

using System;
namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char ch;
Console.WriteLine("Enter an alphabet");
ch = Convert.ToChar(Console.ReadLine());

switch(Char.ToLower(ch))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
break;
}
}
}
}

Example 3: Simple calculator program using C# switch Statement


using System;

namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char op;
double first, second, result;

Console.Write("Enter first number: ");


first = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter second number: ");
second = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter operator (+, -, *, /): ");
op = (char)Console.Read();

switch(op)
{
case '+':
result = first + second;
Console.WriteLine("{0} + {1} = {2}", first, second, result);
break;

case '-':
result = first - second;
Console.WriteLine("{0} - {1} = {2}", first, second, result);
break;

case '*':
result = first * second;
Console.WriteLine("{0} * {1} = {2}", first, second, result);
break;

case '/':
result = first / second;
Console.WriteLine("{0} / {1} = {2}", first, second, result);
break;

default:
Console.WriteLine("Invalid Operator");
break;

}
}}}

CONCEPT 2: C# Methods
A method is a block of code that performs a specific task. Suppose you need to create a
program to create a circle and color it.

Declaring a Method in C#
returnType methodName(parameters) {

// method body

C# Function Syntax
<access-specifier><return-type>FunctionName(<parameters>)

// function body

// return statement

}
returnType - It specifies what type of value a method returns. For example, if a method has an
int return type then it returns an int value.

If the method does not return a value, its return type is void.

methodName - It is an identifier that is used to refer to the particular method in a program.

method body - It includes the programming statements that are used to perform some tasks.
The method body is enclosed inside the curly braces { }

void display() {

// code

Calling a Method in C#
In the above example, we have declared a method named display(). Now, to use the method,
we need to call it.

// calls the method within the class that holds Main ()

display();
C# Methods Parameters
In C#, we can also create a method that accepts some value. These values are called method
parameters. For example,

int addNumber(int a, int b) {

//code

If a method is created with parameters, we need to pass the corresponding values(arguments)


while calling the method. For example,

// call the method within the class that holds Main ()

addNumber(100, 100);

Example: C# Method
using System;

namespace Method {

class Program {

// method declaration

public void display() {

Console.WriteLine("Hello World");

static void Main(string[] args) {

// create class object

Program p1 = new Program();

//call method

p1.display();

Console.ReadLine();

2.1 C# Function: Using Without Parameters and Without Return Type


A function that does not return any value specifies void type as a return type. In the following
example, a function is created without return type.

using System;

namespace FunctionExample

class Program
{

// User defined function without return type

public void Show() // No Parameter

Console.WriteLine("This is non parameterized function");

// No return statement

// Main function, execution entry point of the program

static void Main(string[] args)

Program program = new Program(); // Creating Object

program.Show(); // Calling Function

2.2 C# Function: Using With Parameters (Arguments) and Without Return Type
// User defined function without return type

public void Show(string message)

Console.WriteLine("Hello " + message);

// No return statement

// Main function, execution entry point of the program

static void Main(string[] args)

{
Program program = new Program(); // Creating Object

program.Show("Rahul Kumar"); // Calling Function

A function can have zero or any number of parameters to get data. In the following example, a
function is created without parameters. A function without parameter is also known as non-
parameterized function.

2.3 C# Function: Using with Parameters (Arguments) and with Return Type
Example 1:

using System;

namespace FunctionExample

class Program

// User defined function

public string Show(string message)

return message;

// Main function, execution entry point of the program

static void Main(string[] args)

Program program = new Program();

string message = program.Show("Rahul Kumar");

Console.WriteLine("Hello "+message);
}

Example 2:

using System;

namespace Method {

class Program {

int addNumber (int a, int b) {

int sum = a + b;

return sum;

static void Main(string[] args) {

// create class object

Program p1 = new Program();

//call method

int sum = p1.addNumber(100,100);

Console.WriteLine("Sum: " + sum);

Console.ReadLine();

2.4 C# Function: Using Without Parameters (Arguments) and with Return Value
using System;

namespace FunctionsSample

class Program_D

public int calculate()

int a = 50, b = 80, sum;

sum = a + b;

return sum:

static void Main(string[] args) // Main function

Program_D addition =new Program_D();

addition.calculate();

Console.WriteLine("Calculating the given to values: " +sum);

CONCEPT 3: C# Class and Object


Classes in C#

A class in C# is an object-oriented program. In object-oriented programming (OOP), we solve


complex problems by dividing them into objects.
Class structure

The following components make up a class in C#.

 Fields: They are class-specific variables that store data or state. They stand in for the
traits or qualities of objects derived from the class.
 Properties: Properties offer restricted access to a class’s fields. They contain the fields
and let you specify logic or validation for getting or setting the data.
 Methods: Within a class, a method is a function that specifies the behavior or
operations that an object is capable of. They contain the activities or features related to
the class.

Fundamental concepts in class

There are three fundamental conceptions associated with classes in object-oriented


programming.

 Encapsulation: It is the process of grouping data and methods within a class, concealing
internal implementation details, and enhancing data security and code maintainability.
 Inheritance: For code reuse, modularity, and extensibility, inheritance refers to a class
that derives its characteristics and behavior from a base or parent class.
 Polymorphism: When objects of several classes are treated as instances of a single base
class, polymorphism is supported, providing flexibility, interchangeability, and method
overriding and overloading.

Access modifiers in C#

Access modifiers in C# control the accessibility of class members (fields, properties, methods).

 Public: Accessible from any part of the code.


 Private: Accessible only within the same class.
 Protected: Accessible within the same class and derived classes.
 Internal: Accessible within the same assembly.
 Protected Internal: Accessible within the same assembly and derived classes.

To work with objects, we need to perform the following activities:

• create a class
• create objects from the class

Create a class in C#

class ClassName {

Here, we have created a class named ClassName. A class can contain: -

fields - variables to store data

methods - functions to perform specific task

class Dog {

//field

string breed;

//method

public void bark () {

In the above example,

Dog - class name

breed - field

bark() – method

C# Objects
An object is an instance of a class. Suppose, we have a class Dog. Bulldog, German Shepherd,
Pug are objects of the class.

Creating an Object of a class


In C#, here's how we create an object of the class.

ClassName obj = new ClassName();

Dog bullDog = new Dog();

Example 1:

using System;

namespace ClassObject {

class Dog {

string breed;

public void bark() {

Console.WriteLine("Bark Bark !!");

static void Main(string[] args) {

// create Dog object

Dog bullDog = new Dog();

// access breed of the Dog

bullDog.breed = "Bull Dog";

Console.WriteLine(bullDog.breed);

// access method of the Dog

bullDog.bark();

Console.ReadLine();

}
Example 2:

using System;

namespace ClassObjectsDemo

class Program

static void Main(string[] args)

//Creating object

Calculator calObject = new Calculator();

//Accessing Calculator class member using Calculator class object

int result = calObject.CalculateSum(10, 20);

Console.WriteLine(result);

Console.ReadKey();

//Defining class or blueprint or template

public class Calculator

public int CalculateSum(int no1, int no2)

return no1 + no2;

}
Example 3:

class Zee

public string name1;

public string address;

public void show()

Console.WriteLine("{0} is in city{1}", name1, " ", address);

class Program

static void Main(string[] args)

Zee n = new Zee();

n.name1 = "harsh";

n.address = "new delhi";

n.show();

Console.ReadLine();

Example 4:

class Test

{
public void print()

Console.WriteLine("Csharp:");

class Program

static void Main(string[] args)

Test t = new Test();

t.print();

Console.ReadLine();

CONCEPT 4: C# Constructor
In C#, a constructor is similar to a method that is invoked when an object of the class is created.
However, unlike methods, a constructor: has the same name as that of the class does not have
any return type.

class Car {

// constructor

Car() {

//code

}
Types of Constructors

There are the following types of constructors:

 Parameterless Constructor
 Parameterized Constructor
 Default Constructor

1. Parameterless Constructor
When we create a constructor without parameters, it is known as a parameterless constructor.
For example,

using System;

namespace Constructor {

class Car {

// parameterless constructor

Car() {

Console.WriteLine("Car Constructor");

static void Main(string[] args) {

// call constructor

new Car();

Console.ReadLine();

}}

2. C# Parameterized Constructor
In C#, a constructor can also accept parameters. It is called a parameterized constructor.

Example 1:
using System;

namespace Constructor {

class Car {

string brand;

int price;

// parameterized constructor

Car(string theBrand, int thePrice) {

brand = theBrand;

price = thePrice;

static void Main(string[] args) {

// call parameterized constructor

Car car1 = new Car("Bugatti", 50000);

Console.WriteLine("Brand: " + car1.brand);

Console.WriteLine("Price: " + car1.price);

Console.ReadLine();

Example 2:

using System;

public class Employee

public int id;

public String name;


public float salary;

public Employee(int i, String n,float s)

id = i;

name = n;

salary = s;

public void display()

Console.WriteLine(id + " " + name+" "+salary);

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee(101, "Sonoo", 890000f);

Employee e2 = new Employee(102, "Mahesh", 490000f);

e1.display();

e2.display();

Example 3:

using System;

namespace ParameterizedConstructorDemo

{
class Sum

private int x;

private int y;

public Sum(int a, int b)

x = a;

y = b;

public int getSum()

return x + y;

class Test

static void Main(string[] args)

Sum s = new Sum(15,9);

Console.WriteLine("Sum: {0}" , s.getSum());

3. Default Constructor
If we have not defined a constructor in our class, then the C# will automatically create a default
constructor with an empty code and no parameters. For example,

using System;

Example 1

namespace Constructor {

class Program {

int a;

static void Main(string[] args) {

// call default constructor

Program p1 = new Program();

Console.WriteLine("Default value of a: " + p1.a);

Console.ReadLine();

Example 2:

using System;

public class Employee

public Employee()

Console.WriteLine("Default Constructor Invoked");

public static void Main(string[] args)


{

Employee e1 = new Employee();

Employee e2 = new Employee();

4. C# Constructor Overloading

In C#, we can create two or more constructor in a class. It is known as constructor overloading.
For example,

using System;

namespace ConstructorOverload {

class Car {

// constructor with no parameter

Car() {

Console.WriteLine("Car constructor");

// constructor with one parameter

Car(string brand) {

Console.WriteLine("Car constructor with one parameter");

Console.WriteLine("Brand: " + brand);

static void Main(string[] args) {

// call constructor with no parameter

Car car = new Car();


Console.WriteLine();

// call constructor with parameter

Car car2 = new Car("Bugatti");

Console.ReadLine();

CONCEPT 5: Inheritance
In C#, inheritance allows us to create a new class from an existing class. It is a key feature of
Object-Oriented Programming (OOP).

The class from which a new class is created is known as the base class (parent or superclass).
And, the new class is called derived class (child or subclass)

The derived class inherits the fields and methods of the base class. This helps with the code
reusability in C#.

How to perform inheritance in C#?

In C#, we use the : symbol to perform inheritance. For example,

class Animal {

// fields and methods

// Dog inherits from Animal

class Dog : Animal {

// fields and methods of Animal

// fields and methods of Dog

}
Example: C# Inheritance

using System;

namespace Inheritance {

// base class

class Animal {

public string name;

public void display() {

Console.WriteLine("I am an animal");

}}

// derived class of Animal

class Dog : Animal {

public void getName() {

Console.WriteLine("My name is " + name);

class Program {

static void Main(string[] args) {

// object of derived class

Dog dogname = new Dog();

// access field and method of base class

dogname.name = "Jasmin";

dogname.display();

// access method from own class

dogname.getName();

Console.ReadLine();

}}
}

Types of inheritance
There are the following types of inheritance:

using System;

public class Animal

public void eat() { Console.WriteLine("Eating..."); }

public class Dog: Animal

public void bark() { Console.WriteLine("Barking..."); }

class TestInheritance2{

public static void Main(string[] args)

Dog d1 = new Dog();

d1.eat();
d1.bark();

using System;

public class Animal

public void eat() { Console.WriteLine("Eating..."); }

public class Dog: Animal

public void bark() { Console.WriteLine("Barking..."); }

public class BabyDog : Dog

public void weep() { Console.WriteLine("Weeping..."); }


}

class TestInheritance2{

public static void Main(string[] args) {

BabyDog d1 = new BabyDog();

d1.eat();

d1.bark();

d1.weep();

// hierarchical inheritance

class Bird {

public void Fly() {

Console.WriteLine("Bird is flying.");

class Eagle : Bird {


public void Hunt() {

Console.WriteLine("Eagle is hunting.");

class Penguin : Bird {

public void Swim() {

Console.WriteLine("Penguin is swimming.");

// main program

class Program {

static void Main(string[] args) {

// hierarchical inheritance

Eagle eagle = new Eagle();

Penguin penguin = new Penguin();

eagle.Fly();

eagle.Hunt();

penguin.Fly();

penguin.Swim();

Console.ReadLine();

4. Multiple Inheritance
namespace LearningInheritance

class Program

interface InterfaceA

//...

interface InterfaceB

//...

class NewClass: InterfaceA, InterfaceB

{
//...

static void Main(string[] args)

//...

}
CONCEPT 6: Polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that enables
objects of different classes to be treated as instances of a common superclass or interface. This
concept fosters code reuse, flexibility, and abstraction, making it an essential tool for software
development.

Understanding Polymorphism: Polymorphism refers to the ability of an object to take on


multiple forms. It allows objects of different types to be accessed and manipulated through a
shared interface or superclass.

Polymorphism through Method Overriding: In C#, polymorphism is commonly achieved


through method overriding. Method overriding occurs when a subclass defines a method that
already exists in its superclass. By doing so, the subclass provides its own implementation of
the method, effectively “overriding” the behavior defined in the superclass.

Let’s explore an example to understand polymorphism through method overriding in C#:

using System;

class Animal

public virtual void MakeSound()

Console.WriteLine("The animal makes a sound.");

class Dog : Animal

public override void MakeSound()

Console.WriteLine("The dog barks.");

}
}

class Cat : Animal

public override void MakeSound()

Console.WriteLine("The cat meows.");

class MainClass

public static void Main(string[] args)

Dog animal1 = new Dog();

Cat animal2 = new Cat();

animal1.MakeSound(); // Output: The dog barks.

animal2.MakeSound(); // Output: The cat meows.

Polymorphism through Method Overloading:

Another way to achieve polymorphism in C# is through method overloading. Method


overloading occurs when a class defines multiple methods with the same name but different
parameters. The appropriate method is chosen based on the arguments passed during
invocation.

Example 1:
using System;

class Calculator

public int Add(int a, int b)

return a + b;

public double Add(double a, double b)

return a + b;

class MainClass

public static void Main(string[] args)

Calculator calculator = new Calculator();

int result1 = calculator.Add(2, 3);

Console.WriteLine("Result 1: " + result1); // Output: Result 1: 5

double result2 = calculator.Add(2.5, 3.7);

Console.WriteLine("Result 2: " + result2); // Output: Result 2: 6.2

}
Example 2:
using System;

namespace PolymorphismApplication {

class Printdata {

void print(int i) {

Console.WriteLine("Printing int: {0}", i );

void print(double f) {

Console.WriteLine("Printing float: {0}" , f);

void print(string s) {

Console.WriteLine("Printing string: {0}", s);

static void Main(string[] args) {

Printdata p = new Printdata();

// Call print to print integer

p.print(5);

// Call print to print float

p.print(500.263);

// Call print to print string

p.print("Hello C++");

Console.ReadKey();

}}
CONCEPT 7: C# interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated.

It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve
fully abstraction because it cannot have method body.

In C#, an interface is defined using the interface keyword. Its implementation must be provided
by class or struct. The class or struct which implements the interface, must provide the
implementation of all the methods declared inside the interface.

Example 1: C# Interface

interface IFile

// method without body

void ReadFile();

void WriteFile(string text);

The above declares an interface named IFile. (It is recommended to start an interface name
with the letter "I" at the beginning of an interface so that it is easy to know that this is an
interface and not a class.) The IFile interface contains two methods, ReadFile() and
WriteFile(string)

Example 2: C# Interface

interface IPolygon {

// method without body

void calculateArea();

}
Here,

 Polygon is the name of the interface.

 We cannot use access modifiers inside an interface.

 All members of an interface are public by default.

 An interface doesn't allow fields.

Implementing an Interface

We cannot create objects of an interface. To use an interface, other classes must implement it.
Same as in C# Inheritance, we use: symbol to implement an interface. For example,

Example Program 1:
using System;

namespace CsharpInterface {

interface IPolygon {

// method without body

void calculateArea(int l, int b);

class Rectangle : IPolygon {

// implementation of methods inside interface

public void calculateArea(int l, int b) {

int area = l * b;

Console.WriteLine("Area of Rectangle: " + area);

}
class Program {

static void Main (string [] args) {

Rectangle r1 = new Rectangle();

r1.calculateArea(100, 200);

Output
Area of Rectangle: 20000

Example Program 2:
using System;

namespace CsharpInterface {

interface IPolygon {

// method without body

void calculateArea(int a, int b);

interface IColor {

void getColor();

// implements two interface

class Rectangle : IPolygon, IColor {


// implementation of IPolygon interface

public void calculateArea(int a, int b) {

int area = a * b;

Console.WriteLine("Area of Rectangle: " + area);

// implementation of IColor interface

public void getColor() {

Console.WriteLine("Red Rectangle");

class Program {

static void Main (string [] args) {

Rectangle r1 = new Rectangle();

r1.calculateArea(100, 200);

r1.getColor();

Output
Area of Rectangle: 20000

Red Rectangle

Example Program 3:
using System;

namespace CsharpInterface {

interface IPolygon {

// method without body

void calculateArea();

// implements interface

class Rectangle : IPolygon {

// implementation of IPolygon interface

public void calculateArea() {

int l = 30;

int b = 90;

int area = l * b;

Console.WriteLine("Area of Rectangle: " + area);

class Square : IPolygon {

// implementation of IPolygon interface

public void calculateArea() {

int l = 30;

int area = l * l;
Console.WriteLine("Area of Square: " + area);

class Program {

static void Main (string [] args) {

Rectangle r1 = new Rectangle();

r1.calculateArea();

Square s1 = new Square();

s1.calculateArea();

Output

Area of Rectangle: 2700

Area of Square: 900

Example Program 4:
interface IFile

void ReadFile();

void WriteFile(string text);


}

class FileInfo : IFile

public void ReadFile()

Console.WriteLine("Reading File");

public void WriteFile(string text)

Console.WriteLine("Writing to file");

public class Program

public static void Main()

IFile file1 = new FileInfo();

FileInfo file2 = new FileInfo();

file1.ReadFile();

file1.WriteFile("content");

file2.ReadFile();

file2.WriteFile("content");
}

Example Program 5:
// Interface

interface IAnimal

// interface method (does not have a body)

void animalSound();

// Pig "implements" the IAnimal interface

class Pig : IAnimal

public void animalSound()

// The body of animalSound() is provided here

Console.WriteLine("The pig says: wee wee");

class Program

static void Main(string[] args)

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();
}

Example Program 6:

// C# program to demonstrate working of

// interface

using System;

// A simple interface

interface Inter1

// method having only declaration

// not definition

void display();

// A class that implements interface.

class testClass : Inter1

// providing the body part of function

public void display()

Console.WriteLine("Read Me!!!!");

}
// Main Method

public static void Main (String []args)

// Creating object

testClass t = new testClass();

// calling method

t.display();

}
Output:

Read Me!!!

Example Program 7:

using System;

// interface declaration

interface IVehicle {

// all are the abstract methods.

void changeGear(int a);

void speedUp(int a);

void applyBrakes(int a);

}
// class implements interface

class Bicycle : IVehicle{

int speed;

int gear;

// to change gear

public void changeGear(int newGear)

gear = newGear;

// to increase speed

public void speedUp(int increment)

speed = speed + increment;

// to decrease speed

public void applyBrakes(int decrement)

speed = speed - decrement;

}
public void printStates()

Console.WriteLine("speed: " + speed +

" gear: " + gear);

// class implements interface

class Bike : IVehicle {

int speed;

int gear;

// to change gear

public void changeGear(int newGear)

gear = newGear;

// to increase speed

public void speedUp(int increment)

speed = speed + increment;

}
// to decrease speed

public void applyBrakes(int decrement){

speed = speed - decrement;

public void printStates()

Console.WriteLine("speed: " + speed +

" gear: " + gear);

class GFG {

// Main Method

public static void Main(String []args)

// creating an instance of Bicycle

// doing some operations

Bicycle bicycle = new Bicycle();

bicycle.changeGear(2);

bicycle.speedUp(3);
bicycle.applyBrakes(1);

Console.WriteLine("Bicycle present state :");

bicycle.printStates();

// creating instance of bike.

Bike bike = new Bike();

bike.changeGear(1);

bike.speedUp(4);

bike.applyBrakes(3);

Console.WriteLine("Bike present state :");

bike.printStates();

}
Output:

Bicycle present state:

speed: 2 gears: 2

Bike present state:

speed: 1 gear: 1

Advantage of Interface:

 It is used to achieve loose coupling.


 It is used to achieve total abstraction.
 To achieve component-based programming
 To achieve multiple inheritance and abstraction.
 Interfaces add a plug and play like architecture into applications.
CONCEPT 8: C# Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable
that can hold a reference to the methods. Delegates in C# are similar to the function pointer in
C/C++. It provides a way which tells which method is to be called when an event is triggered.

For example, if you click on a Button on a form (Windows Form application), the program would
call a specific method. In simple words, it is a type that represents references to methods with a
particular parameter list and return type and then calls the method in a program for execution
when it is needed.

Important Points About Delegates:

 Provides a good way to encapsulate the methods.


 Delegates are the library class in System namespace.
 These are the type-safe pointer of any method.
 Delegates are mainly used in implementing the call-back methods and events.
 Delegates can be chained together as two or more methods can be called on a single
event.
 It doesn’t care about the class of the object that it references.
 Delegates can also be used in “anonymous methods” invocation.

Declaration of Delegates

Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.

Syntax:

[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

Instantiation & Invocation of Delegates

After declaring a delegate, a delegate object is created with the help of new keyword. Once a
delegate is instantiated, a method call made to the delegate is pass by the delegate to that
method. The parameters passed to the delegate by the caller are passed to the method, and the
return value, if any, from the method, is returned to the caller by the delegate. This is known as
invoking the delegate.

Syntax:

[delegate_name] [instance_name] = new [delegate_name](calling_method_name);

Example:

add_number add_delegate = new add_number(obj.sum);

Example Program 1:

using System;

namespace Dit {

// declare class " Calculator "

class Calculator {

// Declaring the delegates

// Here return type and parameter type should

// be same as the return type and parameter type

// of the two methods

// "addnum" and "subnum" are two delegate names

public delegate void addnum(int a, int b);

public delegate void subnum(int a, int b);

// method "sum"

public void sum(int a, int b)


{

Console.WriteLine("(100 + 40) = {0}", a + b);

// method "subtract"

public void subtract(int a, int b)

Console.WriteLine("(100 - 60) = {0}", a - b);

// Main Method

public static void Main(String []args)

// creating object "obj" of class " Calculator"

Calculator obj = new Calculator ();

// creating object of delegate, name as "del_obj1" for method "sum" and "del_obj2" for
method "subtract" &

// pass the parameter as the two methods by class object "obj"

// instantiating the delegates

addnum del_obj1 = new addnum(obj.sum);

subnum del_obj2 = new subnum(obj.subtract);

// pass the values to the methods by delegate object

del_obj1(100, 40);

del_obj2(100, 60);
// These can be written as using

// "Invoke" method

// del_obj1.Invoke(100, 40);

// del_obj2.Invoke(100, 60);

}
Output:

(100 + 40) = 140

(100 - 60) = 40

Delegate Interface

It could be a method only. It contains both methods and properties.

If a class implements an interface, then it will


It can be applied to one method at a time. implement all the methods related to that
interface.

Interface is used when your class implements


If a delegate available in your scope you can use it.
that interface, otherwise not.

Delegates can me implemented any number of


Interface can be implemented only one time.
times.

It is used to handling events. It is not used for handling events.


Delegate Interface

It can access anonymous methods. It can not access anonymous methods.

When you access the method using delegates you When you access the method you need the
do not require any access to the object of the class object of the class which implemented an
where the method is defined. interface.

It does not support inheritance. It supports inheritance.

It can wrap static methods and sealed class It does not wrap static methods and sealed
methods class methods..

It created at run time. It created at compile time.

If the method of interface implemented, then


It can implement any method that provides the
the same name and signature method
same signature with the given delegate.
override.

It can wrap any method whose signature is similar A class can implement any number of
to the delegate and does not consider which from interfaces, but can only override those
class it belongs. methods which belongs to the interfaces.

You might also like