Nothing Special   »   [go: up one dir, main page]

Using Using Using Namespace Class Int Public Void: C# Example Class & Object

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 44

C# Example

Class & Object

This Example demonstrates how to call Non-static Member of class using object.

 Write a Program to Add two numbers.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication4
{
class Program
{
int a, b, c;
public void GetData()
{
Console.Write("Enter First Number :");
a = int.Parse(Console.ReadLine());
Console.Write("Enter Second Number :");
b = int.Parse(Console.ReadLine());

public void Sum()


{
c = a + b;
}

public void Display()


{
Console.WriteLine("Addition :" + c);
}
static void Main(string[] args)
{
Program p = new Program();
p.GetData();
p.Sum();
p.Display();
}
}
}

Static & Not-Static Member

Static Member can be access directly with the class name.


To Access Non-static member you have to create an object of
class. Static Member can access only static Variable or static
function.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication4
{
class Program
{
int a = 10;
static int b = 20;

public static void Display()


{
Program p = new Program();
Console.WriteLine(p.a);
Console.WriteLine(b);
}
static void Main(string[] args)
{
Program.Display();

}
}
}

IF Condition:

Q. Enter Cost price and selling price of an item from the user. WAP to check that seller has
made profit or Loss.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication4
{
class Program
{
int cp, sp;
public void GetData()
{
Console.Write("Enter Cost Price :");
cp = int.Parse(Console.ReadLine());
Console.Write("Enter Selling Price :");
sp = int.Parse(Console.ReadLine());
}

public void Check()


{
if (cp > sp)
Console.WriteLine("Seller has made Loss");
else
Console.WriteLine("Seller has made Profit");
}
static void Main(string[] args)
{
Program p = new Program();
p.GetData();
p.Check();
}
}
}

Q. Enter Basic salary from the user. WAP to calculate DA and HRA on the following
Conditions:

Salary DA HRA
<=2000 10% 20%
>2000 && <=5000 20% 30%
>5000 && <=10000 30% 40%
>10000 50% 50%

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
float sal, da, hra, total;
public void GetSal()
{
Console.Write("Enter Basic Salary :");
sal = float.Parse(Console.ReadLine());
}

public void Calculate()


{
if (sal <= 2000)
{
da = sal * 10 / 100;
hra = sal * 20 / 100;
}
else
{
if (sal > 2000 && sal <= 5000)
{
da = sal * 20 / 100;
hra = sal * 30 / 100;
}
else
{
if (sal > 5000 && sal <= 10000)
{
da = sal * 30 / 100;
hra = sal * 40 / 100;
}
else
{
da = sal * 50 / 100;
hra = sal * 50 / 100;
}
}
}
total = sal + da + hra;
}

public void Display()


{
Console.WriteLine("DA={0},HRA={1},Total Salary
:{2}", da, hra, total);
}

static void Main(string[] args)


{
Program p = new Program();
p.GetSal();
p.Calculate();
p.Display();
}
}
}

Array:

Array is a collection of similar data type element. An int Array can contain only int values, a
string array can contain only string values and so on….

Single Dimension:

Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace MyArray
{
class Class1
{
int[] a;

public void GetSize()


{
int size;
Console.Write("Enter Array Size ");
size = int.Parse(Console.ReadLine());
a = new int[size];
}
public void GetData()
{
for (int i = 0; i < a.Length; i++)
{
Console.Write("Enter Value :");
a[i] = int.Parse(Console.ReadLine());
}
}

public void Display()


{
Array.Sort(a); // Ascending Order
Array.Reverse(a); // Reverser Order
for (int i = 0; i < a.Length; i++)
Console.WriteLine(a[i]);
}

}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace MyArray
{

class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.GetSize();
c.GetData();
c.Display();
}
}
}

Two Dimension Array

Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace MyArray2
{
class Class1
{
int[,]a;
int row, col;

public void GetSize()


{
Console.Write("Enter Number of Rows :");
row = int.Parse(Console.ReadLine());
Console.Write("Enter Number of Columns :");
col = int.Parse(Console.ReadLine());
a = new int[row, col];
}

public void GetData()


{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Console.Write("Enter Value :");
a[i, j] = int.Parse(Console.ReadLine());
}
}
}

public void Display()


{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Console.Write("\t" + a[i, j]);
}
Console.WriteLine();
}
}

}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace MyArray2
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.GetSize();
c.GetData();
c.Display();
}
}
}

Jagged Array:

Jagged Array is also known as variable size array or in other words we can say Jagged array is
a collection of single dimension array where each row can contain different number of
elements.

[0][0] [0][1] [0][2]


[1][0] [1][1] [1][2] [1][3]
[2][0] [2][1]

Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace MyArray
{
class Class1
{
int[][] a;
int size;
public void GetSize()
{

Console.Write("Enter Number of Rows: ");


size = int.Parse(Console.ReadLine());
a = new int[size][];
int col;
for (int i = 0; i < size; i++)
{
Console.Write("Enter Columns for Row " + (i + 1)+ ":");
col = int.Parse(Console.ReadLine());
a[i] = new int[col];
}
}
public void GetData()
{
for(int i=0;i<size;i++)
{
for (int j = 0; j < a[i].Length; j++)
{
Console.Write("Enter Value for Row "+(i+1)+":");
a[i][j] = int.Parse(Console.ReadLine());
}
}
}

public void Display()


{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < a[i].Length; j++)
{
Console.Write("\t"+a[i][j]);
}
Console.WriteLine();
}
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace MyArray
{

class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.GetSize();
c.GetData();
c.Display();
}
}
}

ref Parameter

We Can’t Pass any Uninitialized varible with ref Parameter.


Using ref parameter we can pass the reference of argument to
function so if we will make any changes in formal argumnet it
will also reflect in actual arguments.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
public void Swap(ref int a, ref int b)
{
int t;
t = a;
a = b;
b = t;
}
static void Main(string[] args)
{
int r = 10, r1 = 20;
Program p = new Program();
Console.WriteLine("Before Swaping r={0},r1={1}", r, r1);
p.Swap(ref r, ref r1);
Console.WriteLine("After Swaping r={0},r1={1}", r, r1);
}
}
}

out Parameters
We Can Pass an Uninitialized varible with out Parameter. Out
keyword is also used to pass parameters as reference.

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
public int SumMul(int a, int b, out int c)
{
c = a * b;
return a + b;
}
static void Main(string[] args)
{
int r = 10, r1 = 20,d;
Program p = new Program();
int k = p.SumMul(r, r1, out d);
Console.WriteLine("Addition :" + k);
Console.WriteLine("Multiply :" + d);

}
}
}
params Parameter

Params keyword is used to works on variable number of


arguments. For example if we want to add variable number of
arguments so either we have to write number of function i.e.
overloading or either we have an alternate i.e. params
parameters. It works only on single dimension array.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication8
{
class Class1
{

public int Sum(params int[] a)


{
int c = 0;
for (int i = 0; I < a.Length; i++)
c = c + a[i];

return c;
}

public void Display(params object[] a)


{
for (int I = 0; I < a.Length; i++)
Console.WriteLine(a[i]);
}

}
}
Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
int k = c.Sum(10, 20,30);
Console.WriteLine(k);
c.Display(100, "Deepak Bhargava", 22000);
}
}
}

Partial Class

Partial class is a new concept of C# 2005. it is used to divide


a class into number of sub-classes with the same name.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
partial class Class1
{
public void Show()
{
Console.WriteLine("Hello");
}
}
}
Class2.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
partial class Class1
{
public void Display()
{
Console.WriteLine("Bye");
}
}
}
Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{
class Program
{

static void Main(string[] args)


{
Class1 c = new Class1();
c.Show();
c.Display();

}
}
}

Static Class

Static class is a class which can contains only static members.


We can not initiate the object of static class.

Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
static class Class1
{
static int a=10;
public static void Show()
{
Console.WriteLine(a);
}

}
}
Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1.Show();
}
}
}

Function Overloading:

Function overloading is the concept of OOPs where we can define


number of functions with the same name within the same class
but signature of functions should be different. Signature
includes type of parameters, number of parameters.
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
public int Sum(int a, int b)
{
return a + b;
}
public int Sum(int a, int b,int c)
{
return a + b + c;
}
}
}
Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
int k = c.Sum(10, 20);
int k1 = c.Sum(10, 20, 30);
Console.WriteLine(k);
Console.WriteLine(k1);
}
}
}

Operator Overloading

Operator overloading is also the concept of OOPs where we can


change the meaning or behaviour of operator. If we want to
apply any operator on user define data type (like objects of
class) in that case we have to change the meaning of the
operator. To achieve this task we will define operator function
to change the behaviour of operator.

Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
int k;
public Class1()
{
k = 0;
}
public Class1(int p)
{
k = p;
}
public static Class1 operator +(Class1 c, Class1 c1)
{
Class1 t = new Class1();
t.k = c.k + c1.k;
return t;
}
public void Show()
{
Console.WriteLine(k);
}

}
}

Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1(10);
Class1 c1 = new Class1(20);
Class1 c2 = c + c1;
c.Show();
c1.Show();
c2.Show();

}
}
}
Constructors

Constructors are special member function whose name is the same


as class name. Constructors executes automatically when you
will initiate an object of class. Constructors are basically
used to initialize the private member or field of class.

 Constructor can’t be inherit.


 Constructor does not have any return type.
 Constructor can’t be virtual.

We can categorized constructors in two ways:

1- Argument wise
a. Default Constructor (Parameterless)
b. Parametrized Constructor
2- Specifier wise
a. Private Constructor
b. Public Constructor
c. Static Constructor

Default Constructor

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication10
{
class Class1
{
public Class1()
{
Console.WriteLine("Constructor Called");
}
}
}
program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
}
}
}
Parameterized Constructor
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication10
{
class Class1
{
int roll;
string name;
public Class1()
{
roll = 0;
name = "";
}
public Class1(int r, string n)
{
roll = r;
name = n;
}
public void Show()
{
Console.WriteLine("Roll Number :{0},Name={1}", roll, name);
}
}
}

Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1(10,"Deepak Bhargava");
c.Show();
}
}
}

Static Constructor

Static Constructors are special constructor it executed on


loading of class without creating or initaiting any object of
class. Basically it is used to initialize the static member of
class.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication10
{
class Class1
{
static int a;
static Class1()
{
a = 100;
}

public static void Show()


{
Console.WriteLine(a);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Class1.Show();
}
}
}

Properties

Properties are also known as Smart field. It is used to works


on class fields. Properties contains two specifiers set and
get. Set specifier is used to initialize the value in field and
get specifier is used to returns the value of field.

 Properties can be static.


 Propertirs can be Readonly or Writeonly.
 Properties can be virtual or abstract.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
int k;
public int Number
{
set
{
k = value;
}
get
{
return k;
}
}

}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.Number = 200;
int k = c.Number;
Console.WriteLine(k);

}
}
}

Read-only Properties
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
int k;
public Class1()
{
k = 0;
}
public Class1(int p)
{
k = p;
}
public int Number
{
get
{
return k;
}
}

}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1(200);
int k = c.Number;
Console.WriteLine(k);

}
}
}

Write-only Properties

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
int k;
public int Number
{
set
{
k = value;
}
}
public int GetData()
{
return k;
}

}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.Number = 200;
int k = c.GetData();
Console.WriteLine(k);

}
}
}

Static Properties

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
static int k;
public static int Number
{
set
{
k = value;
}
get
{
return k;
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1.Number = 200;
int k = Class1.Number;
Console.WriteLine(k);

}
}
}

Indexer

Indexer is also known as Smart Array. Structure wise Indexer is


same as Properties but there are some differences between
Properties and Indexers.

 Properties has a unique name but Indexer does not have any
name it always define by “this” keyword.
 Properties works on class variable (field) but Indexer
works on Array.
 Properties can be static but Indexer can’t be static
 Properties can be virtual but Indexer can’t be virtual.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
int[] a = new int[3];

public int this[int index]


{
set
{
a[index] = value;
}
get
{
return a[index];
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c[0] = 10;
c[1] = 20;
c[2] = 30;

for (int i = 0; i < 3; i++)


Console.WriteLine(c[i]);

}
}
}

Indexer for Two-Dimension Array

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
int[,] a = new int[2,2];

public int this[int i,int j]


{
set
{
a[i,j] = value;
}
get
{
return a[i,j];
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c[0,0] = 10;
c[0,1] = 20;
c[1,0] = 30;
c[1, 1] = 40;

for (int i = 0; i < 2; i++)


{
for (int j = 0; j < 2; j++)
{
Console.Write("\t"+c[i, j]);
}
Console.WriteLine();
}

}
}
}

Inheritance

Inheritance is the concept to inherit the properties of one


class in to another class. In short we can say Inheritance
means Reusability of data.

1-Single Inheritance

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
public void Show()
{
Console.WriteLine("Hello");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program:Class1
{
public void Display()
{
Console.WriteLine("Bye");
}
static void Main(string[] args)
{
Program p = new Program();
p.Show();
p.Display();

}
}
}

2- MultiLevel Inheritance
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
public void Show()
{
Console.WriteLine("Hello");
}

}
}
Class2.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class2:Class1
{
public void Display()
{
Console.WriteLine("Bye");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program:Class2
{
static void Main(string[] args)
{
Program p = new Program();
p.Show();
p.Display();

}
}
}

Virtual Function

Virtual function always define inside the base class only and
this virtual function can be override in derived class so using
this concept we will get the two copy of same function in
derived class this is also known as Overriding.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
public virtual void Show()
{
Console.WriteLine("Hello");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program:Class1
{
public new void Show()
{
Console.WriteLine("Bye");
}
static void Main(string[] args)
{
Class1 c = new Class1();
c.Show();
Program p = new Program();
p.Show();

}
}
}

Example 2:
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Class1
{
public virtual void Show()
{
Console.WriteLine("Hello");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
class Program:Class1
{
public override void Show()
{
Console.WriteLine("Bye");
}
static void Main(string[] args)
{
Class1 c = new Class1();
c.Show();
c = new Program();
c.Show();

}
}
}

Abstract Class

Abstarct class can contains two types of function:


 Abstract function : does not have any definition of
function
 Non-abstarct function : has definition or body of function

You can’t initiate the function of abstarct class. You have to


inherit this class where you have to override all abstract
functions of base class.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace AbstractClassExample
{
abstract class Class1
{
public void Show()
{
Console.WriteLine("Hello");
}
public abstract void Display();
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace AbstractClassExample
{
class Program:Class1
{
public override void Display()
{
Console.WriteLine("Dispay() of Base Class");
}
static void Main(string[] args)
{
Program p = new Program();
p.Show();
p.Display();
}
}
}

Interface

Interface ia a user define data type where we can declare only


abstarct functions. Like abstarct class we can’t initiate the
object of interface. It’s used only for inheritance. We can not
use abstarct keyword for function inside the interface. We
can’t inherit more than one classes in a class but we can
onherit more than one interface inside the class. It’s
alternate for multiple inheritance.

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace AbstractClassExample
{
interface abc
{
void Show();
void Display();
}

class Program:abc
{
public void Show()
{
Console.WriteLine(“Hello”);
}

public void Display()


{
Console.WriteLine(“Bye”);
}
static void Main(string[] args)
{
Program p = new Program();
p.Show();
p.Display();
}
}
}

Example of more than one interface

Program.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractClassExample
{
interface abc
{
void Show();

}
interface xyz
{
void Display();
}

class Program:abc,xyz
{
public void Show()
{
Console.WriteLine("Hello");
}

public void Display()


{
Console.WriteLine("Bye");
}
static void Main(string[] args)
{
Program p = new Program();
p.Show();
p.Display();
}
}
}

How to remove ambiguity if more than one interface contain same


function signature?

Solution:
Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace AbstractClassExample
{
interface abc
{
void Show();

interface xyz
{
void Show();
}

class Program:abc,xyz
{
void abc.Show()
{
Console.WriteLine("Hello");
}

void xyz.Show()
{
Console.WriteLine("Bye");
}
static void Main(string[] args)
{
abc a = new Program();
// Call abc.Show()
a.Show();
xyz z = new Program();
//Call xyz.Show()
z.Show();

}
}
}

Sealed Class
Sealed class is a final class i.e. we can’t inherit sealed
class.

 Sealed class does not support virtual function.


 Sealed class does not support abstract function.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace SealedClassExample
{
sealed class Class1
{
public void Show()
{
Console.WriteLine("Hello");
}
public void Display()
{
Console.WriteLine("Bye");
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace SealedClassExample
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.Show();
c.Display();
}

}
}

Sealed Function

Sealed function can’t be override in derived class or in other


words we can say sealed functions can’t be inherits.

Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication7
{
class Class1
{
public virtual void Show()
{
Console.WriteLine("Show() of Class1");
}
}
}

Class2.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication7
{
class Class2:Class1
{
public sealed override void Show()
{
Console.WriteLine("Show() of Class2");
}

}
}

Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.Show();
c = new Class2();
c.Show();
}
}
}

Note: Now we can not override Show() in Program Class.

Structure

Structure is an user define data type like class it can also


contains variables, functions and constructors but there are
some differences between class and structure.

Structure is value type but class is reference type.


Structure does not support destructor but class supports
destructor.
 We can’t override default constructor in structure because
structure always provide default constructor but we can
override default constructor in class.
 Structure does not support inheritance but class support
inheritance.
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication10
{
// Structure is Value Type
struct Emp
{
public int emp_id;
public string name;
public void Show()
{
Console.WriteLine("Emp ID={0},Name={1}", emp_id, name);
}
}
class Program
{
static void Main(string[] args)
{
Emp e;
e.emp_id = 100;
e.name = "Deepak Bhargava";
e.Show();
Emp e1 = e;
e1.Show();
// When we make any change in one object
//it will not reflact on another object
e.emp_id = 200;
e.name = "Aman";
e.Show();
e1.Show();
}
}
}

Collection:

Collection is used to store number of values inside the object


like an array but it can contain any type of value i.e.
collection always takes value as an object type.

ArrayList

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication10
{

class Program
{
static void Main(string[] args)
{
ArrayList a = new ArrayList();
a.Add("Deepak");
a.Add(10);
a.Add("Raj");
foreach (object i in a)
Console.WriteLine(i);

a.Remove(10); // To Remove from the Collection


Console.WriteLine();
foreach (object i in a)
Console.WriteLine(i);

a.Insert(1, 25); // To insert value at position 1


Console.WriteLine();
foreach (object i in a)
Console.WriteLine(i);

a.RemoveAt(1); // To Remove value by index number


Console.WriteLine();
foreach (object i in a)
Console.WriteLine(i);
// Count Total number of item of collection
Console.WriteLine("Total Items :"+a.Count);

}
}
}

Stack
Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
Stack s = new Stack();
s.Push(10); // To insert Element
s.Push(20);
s.Push(30);
foreach (object i in s)
Console.WriteLine(i);

s.Pop(); // To Remove Element


Console.WriteLine();
foreach (object i in s)
Console.WriteLine(i);
}
}
}

Queue
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue(10); //To Insert Value
q.Enqueue(20);
q.Enqueue(30);

foreach (object i in q)
Console.WriteLine(i);

q.Dequeue(); // To Remove Element


Console.WriteLine();
foreach (object i in q)
Console.WriteLine(i);
}
}
}

HashTable
Class1.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication13
{
class Class1
{
int id;
string name;
public Class1()
{
id = 0;
name = "";
}
public Class1(int i, string n)
{
id = i;
name = n;
}
public void Show()
{
Console.WriteLine("Emp ID :{0},Name :{1}", id, name);
}
}
}
Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
Hashtable t = new Hashtable();
t.Add(1, new Class1(100, "Deepak Bhargava"));
t.Add(2, new Class1(200, "Pradeep Gaur"));
for (int i = 1; i <= 2; i++)
{
Class1 k = (Class1)t[i];
k.Show();
}
}
}
}

Reflaction

Reflaction is used to get the information or metadata of


Assembly at run time. To use this concept we have to include a
System.Reflaction namespcae. This namespace contains so many
classes to get all information at run time.

ClassLibrary6.dll
using System;
using System.Collections.Generic;
using System.Text;

namespace ClassLibrary6
{
public class Class1
{
public int Sum(int a, int b)
{
return a + b;
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
// To Load Dll file
Assembly asm =
Assembly.LoadFile(@"d:\ClassLibrary6\Bin\Debug\ClassLibrary6.dl
l");
//To Get All Class Names
Type[] t = asm.GetTypes();
//To Get All Constructors of Class
ConstructorInfo[] ci = t[0].GetConstructors();
//To Call Default Constructor to Create an Object
object ob = ci[0].Invoke(null);
//To Get All Methods of Class
MethodInfo[] mi = t[0].GetMethods();
int pos=0;
// To Search the Position of Sum()
foreach (MethodInfo i in mi)
{
if (i.Name == "Sum")
break;
else
pos++;
}
// To Get parameters of Sum()
ParameterInfo[] pi = mi[pos].GetParameters();
object[] a = new object[pi.Length];
// To Get Values from the User
for (int i = 0; i < pi.Length; i++)
{
Console.Write("Enter Value :");
a[i] = int.Parse(Console.ReadLine());
}
// To Call Sum()
object k = mi[pos].Invoke(ob, a);
Console.WriteLine("Addition :" + k);
}
}
}
Delegate
Delegate is type-safe function pointer. It contains the address
of function. Type safe means a delegate can contain the address
of only that function whose signature should match with
delegate signature.

Single Cast Delegate

Single cast delegate can contains the address of only one


function at a time.
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Class1
{
public void Show()
{
Console.WriteLine("Show Function");
}
public int Sum(int a, int b)
{
return a + b;
}
}
}

Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
public delegate void MyDelegate1(); //Declaration
public delegate int MyDelagate2(int a, int b);
static void Main(string[] args)
{
Class1 c = new Class1();
// Initialization of Delegate
MyDelegate1 d1 = new MyDelegate1(c.Show);
MyDelagate2 d2 = new MyDelagate2(c.Sum);

// Calling delagate
d1();
int k = d2(20, 35);
Console.WriteLine("Addition :" + k);
}
}
}

MultiCast delegate

Multi cast delegate can contains the address of more than one
function at a time but all functions should have same
signature. Multi cast delegate is used for Event Handling where
one control contains the addresses of so many events.

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Class1
{
public void Show()
{
Console.WriteLine("Show Function");
}
public void Display()
{
Console.WriteLine("Display Function");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
public delegate void MyDelegate1(); //Declaration

static void Main(string[] args)


{
Class1 c = new Class1();
MyDelegate1 d1 = new MyDelegate1(c.Show);
d1(); // Show Function
d1 += new MyDelegate1(c.Display);
d1(); // Show Function, Display Function
d1 -= new MyDelegate1(c.Show);
d1(); // Display Function
}
}
}

Event Handling Using MultiCast Delegate

Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button b = new Button();
b.Text = "Click Me";
b.Location = new System.Drawing.Point(61, 59);
b.Size = new System.Drawing.Size(143, 26);
b.Click+=new EventHandler(ShowDataOnClick);
b.MouseHover += new EventHandler(ShowDataOnMouseOver);
this.Controls.Add(b);
}

private void ShowDataOnClick(object sender, EventArgs e)


{
MessageBox.Show("Clicked");
}

private void ShowDataOnMouseOver(object sender, EventArgs e)


{
MessageBox.Show("Mouse Over");
}
}
}

Exception Handling

Exceptions are the run time errors which occurs on a paritucal


conditions at run time. For ex: Divide by zero , File not found
etc.

In .Net there are two types of Exceptions

System Exception : Generated by the system


Application Exception : Generated by the user.

System Exception

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ExceptionHandling
{
class Class1
{
int num1=10,num2,ans;
public void GetData()
{
try
{
Console.Write("Enter a number :");
num2 = int.Parse(Console.ReadLine());
ans = num1 / num2;
Console.WriteLine("Answer :" + ans);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
// Exception is the base class for all exception
// This Class can catch all type of errors
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

Application Exception:

Application Exception generated by the user. For ex: if we


wants to get a number from the user between 1 and 100. if user
enters wrong value there should be one exception.

UserException.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ExceptionHandling
{
class UserException:ApplicationException
{
public UserException(string s)
: base(s)
{
}
}
}

Class1.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ExceptionHandling
{
class Class1
{
int num1;
public void GetData()
{
try
{
Console.Write("Enter a number :");
num1 = int.Parse(Console.ReadLine());
if (num1 < 1 || num1 > 100)
// Throw Application Exception
throw new UserException("Number Should be between
1 and 100");
else
Console.WriteLine("Thankyou");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
catch (UserException e)
{
Console.WriteLine(e.Message);
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace ExceptionHandling
{
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.GetData();
}
}
}

Generic Collection

Generic Collection is a special collection it stores only one


data type values like an array. But it contains all the
functions of collection class like Add, Remove, RemoveAt,
Insert etc.

Program.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace GenericCollection
{
class Program
{
static void Main(string[] args)
{
List<int> MyCol = new List<int>();
// We can Add Only integer values
MyCol.Add(10);
MyCol.Add(20);
MyCol.Add(30);

foreach (int i in MyCol)


Console.WriteLine(i);
}
}
}

You might also like