C# Notes
C# Notes
The C# for loop is same as C/C++. We can initialize variable, check condition
and increment/decrement value.
Syntax:
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);
}
}
}
}
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");
}
}
}
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.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");
}
}
}
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");
}
}
}
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");
}
}
}
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
}
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());
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);
}
}
}
}
}
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;
}
}
}
}
namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char op;
double first, second, result;
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.
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.
display();
C# Methods Parameters
In C#, we can also create a method that accepts some value. These values are called method
parameters. For example,
//code
addNumber(100, 100);
Example: C# Method
using System;
namespace Method {
class Program {
// method declaration
Console.WriteLine("Hello World");
//call method
p1.display();
Console.ReadLine();
using System;
namespace FunctionExample
class Program
{
// No return statement
2.2 C# Function: Using With Parameters (Arguments) and Without Return Type
// User defined function without return type
// No return statement
{
Program program = new Program(); // Creating Object
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
return message;
Console.WriteLine("Hello "+message);
}
Example 2:
using System;
namespace Method {
class Program {
int sum = a + b;
return sum;
//call method
Console.ReadLine();
2.4 C# Function: Using Without Parameters (Arguments) and with Return Value
using System;
namespace FunctionsSample
class Program_D
sum = a + b;
return sum:
addition.calculate();
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.
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).
• create a class
• create objects from the class
Create a class in C#
class ClassName {
class Dog {
//field
string breed;
//method
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.
Example 1:
using System;
namespace ClassObject {
class Dog {
string breed;
Console.WriteLine(bullDog.breed);
bullDog.bark();
Console.ReadLine();
}
Example 2:
using System;
namespace ClassObjectsDemo
class Program
//Creating object
Console.WriteLine(result);
Console.ReadKey();
}
Example 3:
class Zee
class Program
n.name1 = "harsh";
n.show();
Console.ReadLine();
Example 4:
class Test
{
public void print()
Console.WriteLine("Csharp:");
class Program
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
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");
// 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
brand = theBrand;
price = thePrice;
Console.ReadLine();
Example 2:
using System;
id = i;
name = n;
salary = s;
class TestEmployee{
e1.display();
e2.display();
Example 3:
using System;
namespace ParameterizedConstructorDemo
{
class Sum
private int x;
private int y;
x = a;
y = b;
return x + y;
class Test
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;
Console.ReadLine();
Example 2:
using System;
public 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 {
Car() {
Console.WriteLine("Car constructor");
Car(string brand) {
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#.
class Animal {
}
Example: C# Inheritance
using System;
namespace Inheritance {
// base class
class Animal {
Console.WriteLine("I am an animal");
}}
class Program {
dogname.name = "Jasmin";
dogname.display();
dogname.getName();
Console.ReadLine();
}}
}
Types of inheritance
There are the following types of inheritance:
using System;
class TestInheritance2{
d1.eat();
d1.bark();
using System;
class TestInheritance2{
d1.eat();
d1.bark();
d1.weep();
// hierarchical inheritance
class Bird {
Console.WriteLine("Bird is flying.");
Console.WriteLine("Eagle is hunting.");
Console.WriteLine("Penguin is swimming.");
// main program
class Program {
// hierarchical inheritance
eagle.Fly();
eagle.Hunt();
penguin.Fly();
penguin.Swim();
Console.ReadLine();
4. Multiple Inheritance
namespace LearningInheritance
class Program
interface InterfaceA
//...
interface InterfaceB
//...
{
//...
//...
}
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.
using System;
class Animal
}
}
class MainClass
Example 1:
using System;
class Calculator
return a + b;
return a + b;
class MainClass
}
Example 2:
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int i) {
void print(double f) {
void print(string s) {
p.print(5);
p.print(500.263);
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
void ReadFile();
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 {
void calculateArea();
}
Here,
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 {
int area = l * b;
}
class Program {
r1.calculateArea(100, 200);
Output
Area of Rectangle: 20000
Example Program 2:
using System;
namespace CsharpInterface {
interface IPolygon {
interface IColor {
void getColor();
int area = a * b;
Console.WriteLine("Red Rectangle");
class Program {
r1.calculateArea(100, 200);
r1.getColor();
Output
Area of Rectangle: 20000
Red Rectangle
Example Program 3:
using System;
namespace CsharpInterface {
interface IPolygon {
void calculateArea();
// implements interface
int l = 30;
int b = 90;
int area = l * b;
int l = 30;
int area = l * l;
Console.WriteLine("Area of Square: " + area);
class Program {
r1.calculateArea();
s1.calculateArea();
Output
Example Program 4:
interface IFile
void ReadFile();
Console.WriteLine("Reading File");
Console.WriteLine("Writing to file");
file1.ReadFile();
file1.WriteFile("content");
file2.ReadFile();
file2.WriteFile("content");
}
Example Program 5:
// Interface
interface IAnimal
void animalSound();
class Program
myPig.animalSound();
}
Example Program 6:
// interface
using System;
// A simple interface
interface Inter1
// not definition
void display();
Console.WriteLine("Read Me!!!!");
}
// Main Method
// Creating object
// calling method
t.display();
}
Output:
Read Me!!!
Example Program 7:
using System;
// interface declaration
interface IVehicle {
}
// class implements interface
int speed;
int gear;
// to change gear
gear = newGear;
// to increase speed
// to decrease speed
}
public void printStates()
int speed;
int gear;
// to change gear
gear = newGear;
// to increase speed
}
// to decrease speed
class GFG {
// Main Method
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
bicycle.printStates();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);
bike.printStates();
}
Output:
speed: 2 gears: 2
speed: 1 gear: 1
Advantage of Interface:
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.
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:
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:
Example:
Example Program 1:
using System;
namespace Dit {
class Calculator {
// method "sum"
// method "subtract"
// Main Method
// creating object of delegate, name as "del_obj1" for method "sum" and "del_obj2" for
method "subtract" &
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 - 60) = 40
Delegate Interface
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 can wrap static methods and sealed class It does not wrap static methods and sealed
methods class methods..
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.