ARTICLE

Object Oriented Programming in C#.Net

Posted by Aakash Bhimani Articles | OOP/OOD October 14, 2013
This article defines Object Oriented Programming in C#.Net.
Reader Level:

Object Oriented Programming in C#.Net

Question 1: What is Object Oriented Programming?

Answer: "Definition"

  • Object Oriented Programming(OOP) provides a way to make programs flexible by providing memory for both Data and Function.
  • So, you can consider an Object as part of memory which is holding the data and operations which can be used to access that data. As Memory partitions are not dependent so objects can be used in different programs without making any changes in them.
  • Some Examples of OOP Languages are C#, VB.NET, JAVA, and C++.

Features of Object Oriented Programming

The features of OOP are:

  • Objects
  • Classes
  • Data Abstraction and Encapsulation
  • Inheritance
  • Polymorphism
  • Dynamic Binding

Object oriented Programming

Organization of Data and Functions in OOP
 

Given below figure shows the organization of data and functions in OOP. Only those Functions can be used to access particular Objects which are associated with it, but Functions of one Object can be used to access functions of some other objects.

Organization of data and functions in OOP

Characteristics of OOP

  • Data gets more importance than Procedure.
  • Programs are divided into objects.
  • Objects are characterized using Data Structures.
  • Data Structures hold the functions which are operating on the data of an object.
  • External Functions can't access the Data as they are made hidden from them.
  • Functions are used by objects to communicate with each other.
  • If required then new Data and Functions can be Added easily.
  • In program design Bottom-Up approach is used.

Question 2: What is an Object?

Answer: "Definition"

  • Objects are Real-World Entities of OOP.
  • A group of features can represent an Object.
  • If anything is in Real World then that will be an Object.
  • An Object can be Visible, Ideological or analytical.
  • Variables are used to store an Objects Identity and State and Methods are used to show it's behavior.
  • Examples of an Object are Pen, People, Table etc.

Object

Objects have the following characteristics:

  1. State
  2. Behavior
  3. Identity
  4. Responsibility

1. State

The state of an object means the current values of all of its attribute, mainly the following two types of states.

1) Static state

Whose value doesn't change over a period of time.

2) Dynamic state

Whose value doesn't change over a period of time.

For Example:  Car

A car is defined by:

  • Color
  • Average
  • Power staric state
  • Fuel type
  • Speed
  • Fuel level dynamic state
  • Gear

2. Behavior

Behavior is how the object acts or reacts, in terms of state changes and operations performed on it.

For Example: Car

The behavior of a car is:

  • Open door
  • Close door
  • Change gear
  • Power on
  • Power off

3. Identity

Identity is how an object is identified.

For Example: Car

A car is identifying by:

  • Color
  • Number plate IDENTIFY CAR
  • Chassis number

4. Responsibility

Responsibility is the role of an object.

For example: Car

The role of a Car is:

To travel from one location to another.

Syntax

Object Syntax

creating Object

Question 3: Class

Answer

  • A class is one of many items or collections. A class contains data members, member functions and access modifiers.
  • A class is also a collection of objects.
  • Several objects have a common state and behavior and thus can be grouped under a single class. For example, a Ford, a Honda, an Accent, and a Toyota can be grouped together under the class Car. Here, a Car is the class whereas Ford, Honda, Accent, Toyota are objects of the class Car.

    Class

  • In C#, the class declaration starts with the class keyword followed by the name of the class.

I. Data member

Some data can be defined inside the class and are all of the data members of this class.

II. Member Function

Some functions can be defined inside the class and are all of the member functions of this class.

The following two special member functions exist in a class.

a) Constructor

A Constructor can be used to initialize the object.

b) Destructor

A Destructor can be used to de-initialize the object.

III. Access Modifier

Access Modifiers provide some restrictions on the data and functions inside the class. There are mainly four types of access modifiers considered in C#.

  1. private
  2. public
  3. protected
  4. internal

Syntax

Class Syntax

Snippet

Field and Method in Class

  • Valid Class Names or Invalid Class Names

Valid and -Invalid Class Names

Demo Program

namespace CLASS_DEMO

{

    class person

    {

        private

        string name;

        int age;

        double salary;

 

        public void getdata()

        {

            Console.Write("Enter Your Name:-");

            name = Console.ReadLine();

            Console.Write("Enter the age:-");

            age = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter the salary:-");

            salary = Convert.ToDouble(Console.ReadLine());

        }

        public void putdata()

        {

            Console.WriteLine("NAME==>" + name);

            Console.WriteLine("AGE==>" + age);

            Console.WriteLine("SALARY==>" + salary);

        }

 

    }

    class Program

    {

        static void Main(string[] args)

        {

            person obj = new person();

            obj.getdata();

            obj.putdata();

 

            Console.ReadLine();

        }

    }

}

Question 4: Encapsulation and data hiding

Answer

  • The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only those functions, that are wrapped in the class, can access it. These functions provide the interface between the object's data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding.
  • Classes provide the idea of encapsulation because classes contain both data and functions.
  • Data hiding is done by using access modifier.

Question 5: Abstractions

Answer

Abstraction refers to the act of representing essential features without including the background details or explanations.
Abstraction is the feature of extracting only the required information from objects. For example, consider a television as an object. It has a manual explaining how to use the television. However, this manual does not show all the technical details of the television, thus giving only an abstraction to the user.

Question 6: Methods

Answer

Methods are function declarations in a class and may be used to perform operations on class variables. They are blocks of code that can take parameters and may or may not return a value. A method implements the behavior of an object, that can be accessed by instantiating the object of the class in which it is defined and then invoking the method. For example, the class Car can have a method break() that represents the "Apply Break" action. To perform the action, the method break() will need to be invoked by an object of the class Car.

Methods

1) Creating Method

Creating Method

2) Types of methods

The following are the main three types of methods declared in C#.

  1. No return value and no parameters
  2. Return value but no parameter
  3. Return value and parameters
  4. No return value but parameters

1. No return value and no parameters

Demo Program

namespace Noreturn_values_with_No_parameter

{

    class multipliction

    {

        //Define Methods

        public void mul()

        {

            int No1, No2, Ans;

            Console.Write("Enter First Number:-");

            No1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            No2 = Convert.ToInt32(Console.ReadLine());

 

            Ans = No1 * No2;

            Console.WriteLine("Multipliction of above two number is:-" + Ans);

        }

    }

    class addition

    {

        //Define Methods

        public static void add()

        {

            int No1, No2, Ans;

            Console.Write("Enter First Number:-");

            No1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            No2 = Convert.ToInt32(Console.ReadLine());

 

            Ans = No1 + No2;

            Console.WriteLine("Addition of above two number is:-" + Ans);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("\nENTER ANY TWO NUMBER FOR Multipliction");

            multipliction obj = new multipliction();

            obj.mul();

            Console.WriteLine("\nENTER ANY TWO NUMBER FOR ADDITION");

            addition.add();

            Console.ReadLine();

        }

    }

}

2. Return value but no parameter

Demo Program
 

namespace return_values_no_parameter

{

    class multipliction

    {

        //Declar Methods

        public int mul()

        {

            int a, b, Ans;

            Console.Write("\nEnter First Number:-");

            a = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            b = Convert.ToInt32(Console.ReadLine());

            Ans = a * b;

            return Ans;

        }

    }

    class addition

    {

        //Declar Methods

        public static int add()

        {

            int a, b, Ans;

            Console.Write("\nEnter First Number:-");

            a = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            b = Convert.ToInt32(Console.ReadLine());

            Ans = a + b;

            return Ans;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("MULTIPLICTION OF TWO NUMBER");

            multipliction obj = new multipliction();

            Console.WriteLine("Multipliction of two number is:-" + obj.mul());

            Console.WriteLine("\nADDITION OF TWO NUMBER");

            Console.WriteLine("Addition of two number is:-" + addition.add());

            Console.ReadLine();

        }

    }

}


3. Return value and parameters

Demo Program
 

namespace return_values_with_parameter

{

    class multipliction

    {

        //Declar Methods

        public int mul(int a, int b)

        {

            return a * b;

        }

    }

    class addition

    {

        //Declar Methods

        public static int add(int a, int b)

        {

            return a + b;

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            int No1, No2, Ans;

            Console.Write("Enter First Number:-");

            No1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            No2 = Convert.ToInt32(Console.ReadLine());

            multipliction obj = new multipliction();

            Ans = obj.mul(No1, No2);

            Console.WriteLine("\nMultipliction of two number is:-" + Ans);

            Ans = addition.add(No1, No2);

            Console.WriteLine("Addition of two number is:-" + Ans);

            Console.ReadLine();

        }

    }

}


4. No return value but parameters

Demo Program

namespace No_return_values_but_get_parameter

{

    class multipliction

    {

        //Declar Methods

        public void mul(int a, int b)

        {

            int Ans;

            Ans = a * b;

            Console.WriteLine("Multipliction of two number is:-" + Ans);

        }

    }

    class addition

    {

        //Declar Methods

        public static void add(int a, int b)

        {

            int Ans;

            Ans = a + b;

            Console.WriteLine("Addition of two number is:-" + Ans);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            int No1, No2;

            Console.Write("Enter First Number:-");

            No1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            No2 = Convert.ToInt32(Console.ReadLine());

            multipliction obj = new multipliction();

            obj.mul(No1, No2);

            addition.add(No1, No2);

            Console.ReadLine();

        }

    }

}


3) Invoking Methods

  • You can invoke a method in a class by creating an object of the class to invoke a method, the object name is followed by a period (.) and the name of the method followed by parentheses.
  • In C#, a method is always invoked from another method. The method in which it is invoked is referred to as the calling method. The invoked method is referred to as the called method. Most of the methods are invoked from the main() method of the class, that is the entry point of program execution.

Invoking Methods

4) Static Methods

A method, by default, is called using an object of the class. However it is possible for a method to be called without creating any objects of the class. This can be done by declaring a method static. A static method is declared using the static keyword. For example, the main() method is a static method and it does not require any instances of the class for it to be invoked. Static methods can directly refer to static variables and other static methods of the class. However, static methods can refer to non-static methods and variables by using an instance of the class.

Static Methods

Syntax

Static Method Syntax

Demo Program

namespace STATIC_METHOD

{

    class Calculate

    {

        public static void Add(int val1, int val2)

        {

            Console.WriteLine(val1 + val2);

        }

        public void Mul(int val1, int val2)

        {

            Console.WriteLine(val1 * val2);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Calculate.Add(10, 20);

            Calculate obj = new Calculate();

            obj.Mul(10, 20);

            Console.ReadLine();

        }

    }

}


Question 7: Inheritances

Answer

  • Reusability is the most important concept in Object Oriented Programming and reusability is done by inheritances.
  • In other words, we can say that the purpose of inheritance is to reuse common methods and attributes among classes without recreating them.
  • Reusability of code enables you to use the same code in various applications with little or no charges. Apart from reusability, inheritance is widely used for:
  • Generalization
  • Specialization
  • Extension
  • Inheritance defined relationships among classes, that share common structures and behavior.
  • Inheritance is one of the processes of creating new classes, called derived classes, from exiting classes, that are often called base classes.


Inheritances

Types of inheritances

Inheritance can be classified into the following types:

  1. Single inheritance
  2. Multilevel inheritance
  3. Hierarchical inheritance
  4. Hybrid inheritance
  5. Multipath inheritance
  6. Multiple inheritances

1) Single inheritance

When one derived class can acquire the property of one base class then it is called single inheritance, as shown in the following figure:

Single inheritance

For example:

1)

namespace single_inheritance
{

    class Animal

    {

        public void Eat()

        {

            Console.WriteLine("Every animal eats something.");

        }

        public void dosomething()

        {

            Console.WriteLine("Every animal does something.");

        }

    }

    class cat : Animal

    {

        static void Main(string[] args)

        {

            cat objcat = new cat();

            objcat.Eat();

            objcat.dosomething();

            Console.ReadLine();

        }

    }

}

2)

namespace single_inheritance

{

    class multipliction

    {

        //Define Methods

        public void mul()

        {

            int No1, No2, Ans;

            Console.Write("Enter First Number:-");

            No1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            No2 = Convert.ToInt32(Console.ReadLine());

 

            Ans = No1 * No2;

            Console.WriteLine("Multipliction of above two number is:-" + Ans);

        }

    }

    class addition : multipliction

    {

        //Define Methods

        public void add()

        {

            int No1, No2, Ans;

            Console.Write("Enter First Number:-");

            No1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Second Number:-");

            No2 = Convert.ToInt32(Console.ReadLine());

 

            Ans = No1 + No2;

            Console.WriteLine("Addition of above two number is:-" + Ans);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            addition objadd = new addition();

            Console.WriteLine("\nENTER ANY TWO NUMBER FOR Multipliction");

            objadd.mul();

            Console.WriteLine("\nENTER ANY TWO NUMBER FOR ADDITION");

            objadd.add();

            Console.ReadLine();

        }

    }

}


2) Multilevel inheritance

Derivation of a class from another derived class is called multilevel inheritance, as shown in the following figure:

Multilevel inheritance

For example:
 

namespace Multilevel_Inheritance

{

    class EmployeeName

    {

        public void Name()

        {

            Console.WriteLine("Name of Employee: \n Raj \n Deep \n Mayur \n");

        }

    }

    class Raj : EmployeeName

    {

 

        public void Rajinfo()

        {

            Console.WriteLine("Name:raj \n Age:23 \n Post:Assi.Manager \n");

        }

    }

    class Deep : Raj

    {

        public void Deepinfo()

        {

            Console.WriteLine("Name:Deep \n Age:30 \n Post:Manager \n");

        }

    }

    class Mayur : Deep

    {

        public void Mayurinfo()

        {

            Console.WriteLine("Name:Mayur \n Age:41 \n Post:HR.Manager \n");

        }

    }

    class cat : Mayur

    {

        static void Main(string[] args)

        {

            Mayur objMayur = new Mayur();

            objMayur.Name();

            objMayur.Rajinfo();

            objMayur.Deepinfo();

            objMayur.Mayurinfo();

            Console.ReadLine();

        }

    }

}

3) Hierarchical inheritance

Derivation of several classes from a single base class is called hierarchical inheritance, as shown in the following figure:

Hierarchical inheritance

For example:
 

namespace Hierarchical_Inheritance

{

    class EmployeeName

    {

        public void Name()

        {

            Console.WriteLine("Name of Employee: \n Raj \n Deep \n Mayur \n");

        }

        public void Rajinfo()

        {

            Console.WriteLine("Name:raj \n Age:23 \n Post:Assi.Manager \n");

        }

        public void Deepinfo()

        {

            Console.WriteLine("Name:Deep \n Age:30 \n Post:Manager \n");

        }

        public void Mayurinfo()

        {

            Console.WriteLine("Name:Mayur \n Age:41 \n Post:HR.Manager \n");

        }

    }

    class Raj : EmployeeName

    {

        public void RajProfile()

        {

            Console.WriteLine("Display Raj Profile: \n");

        }

    }

    class Deep : EmployeeName

    {

        public void DeepProfile()

        {

            Console.WriteLine("Display Deep Profile: \n");

        }

    }

    class Mayur : EmployeeName

    {

        public void MayurProfile()

        {

            Console.WriteLine("Display Mayur Profile: \n");

        }

    }

    class cat

    {

        static void Main(string[] args)

        {

            EmployeeName obj = new EmployeeName();

            Raj objRaj = new Raj();

            Deep objDeep = new Deep();

            Mayur objMayur = new Mayur();

            obj.Name();

            objRaj.RajProfile();

            objRaj.Rajinfo();

            objDeep.DeepProfile();

            objDeep.Deepinfo();

            objMayur.MayurProfile();

            objMayur.Mayurinfo();

            Console.ReadLine();

        }

    }

}

4) Hybrid inheritance

Derivation of a class involving more than one type of inheritance is known as hybrid Inheritance, as shown in the following figure:

Hybrid inheritance

For example:
 

namespace Multilevel_Inheritance

{

    class EmployeeName

    {

        public void Name()

        {

            Console.WriteLine("Name of Employee: \n Raj \n Deep \n Mayur \n Mariya \n");

        }

        public void Rajinfo()

        {

            Console.WriteLine("Name:raj \n Age:23 \n Post:Assi.Manager \n");

        }

        public void Deepinfo()

        {

            Console.WriteLine("Name:Deep \n Age:30 \n Post:Manager \n");

        }

        public void Mayurinfo()

        {

            Console.WriteLine("Name:Mayur \n Age:41 \n Post:HR.Manager \n");

        }

        public void Mariyainfo()

        {

            Console.WriteLine("Name:Mariya \n Age:32 \n Post:Interview.Handler \n");

        }

    }

    class Raj : EmployeeName

    {

 

        public void RajProfile()

        {

            Console.WriteLine("Display Raj Profile: \n");

        }

    }

    class Deep : EmployeeName

    {

        public void DeepProfile()

        {

            Console.WriteLine("Display Deep Profile: \n");

        }

    }

    class Mayur : EmployeeName

    {

        public void MayurProfile()

        {

            Console.WriteLine("Display Mayur Profile: \n");

        }

    }

    class Mariya : Mayur

    {

        public void MariyaProfile()

        {

            Console.WriteLine("Display Mariya Profile: \n");

        }

    }

    class cat

    {

        static void Main(string[] args)

        {

            EmployeeName obj = new EmployeeName();

            Raj objRaj = new Raj();

            Deep objDeep = new Deep();

            Mayur objMayur = new Mayur();

            Mariya objMariya = new Mariya();

            obj.Name();

            objRaj.RajProfile();

            objRaj.Rajinfo();

            objDeep.DeepProfile();

            objDeep.Deepinfo();

            objMayur.MayurProfile();

            objMayur.Mayurinfo();

            objMariya.MariyaProfile();

            objMariya.Mariyainfo();

 

            Console.ReadLine();

        }

    }

}

5) Multipath inheritance

Derivation of a class from other derived classes, that are derived from the same base class, is called multipath inheritance.

6) Multiple inheritances

Multiple inheritances cannot be supported in C# therefore we use interfaces. We will explain later what an interface is.

Question 8: Polymorphism

Answer

  • Polymorphism is derived from two Greek words, namely poly and morphos. Poly means many and morphos means forms. Polymorphism means existing in multiple forms. Polymorphism is the ability to take more than one form.
  • Polymorphism can be classified into the two categories, compile-time polymorphism and run-time polymorphism. The following table shows the differences side-by-side between compile-time and run-time polymorphism.

Polymorphism

Types of Polymorphism

1. Compile-time Polymorphism

Compile-time polymorphism is implemented through method overloading.

You can implement polymorphism in C# through method overloading and overriding. You can create multiple methods with the same name in a class or in various classes having various method bodies or different signatures. Methods having the same name but different signatures in a class are referred to as overloaded methods. Here the same method performs the same function on various values.

Example

namespace Method_Overloading_1

{

    class Area

    {

        static public int CalculateArea(int len, int wide)

        {

            return len * wide;

        }

        static public double CalculateArea(double valone, double valtwo)

        {

            return 0.5 * valone * valtwo;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            int length = 10;

            int breath = 22;

 

            double tbase = 2.5;

            double theight = 1.5;

 

            Console.WriteLine("Area of Rectangle:-" + Area.CalculateArea(length, breath));

            Console.WriteLine("Area of triangle:-" + Area.CalculateArea(tbase, theight));

            Console.ReadLine();

        }

    }

}

2. Run-time Polymorphism

Run-time polymorphism is implemented by virtual methods and overriding.

Methods inherited from the base class in the derived class and modified within the derived class are referred to as overridden methods. Here, only the body of the method changes in order to function depending on the required output.

Example
 

namespace Virtual_Method1

{

    class Circle

    {

        protected const double PI = 3.14;

        protected double Radious = 14.9;

        public virtual double Area()

        {

            return PI * Radious * Radious;

        }

    }

    class Cone : Circle

    {

        protected double Side = 10.2;

        public override double Area()

        {

            return PI * Radious * Radious;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Circle obj1 = new Circle();

            Console.WriteLine("Area is:-" + obj1.Area());

            Circle obj2 = new Cone();

            Console.WriteLine("Area is:-" + obj2.Area());

            Console.ReadLine();

 

        }

    }

}

namespace Virtual_Method_2

{

    class Student

    {

        string _studentName = "James";

        string _address = "California";

        public virtual void printdetails()

        {

            Console.WriteLine("Student Name:-" + _studentName);

            Console.WriteLine("Address:-" + _address);

        }

    }

    class Grade : Student

    {

        string _class = "Four";

        float _percent = 71.25F;

        public override void printdetails()

        {

            Console.WriteLine("Student Name:-" + _class);

            Console.WriteLine("Address:-" + _percent);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Student obj1 = new Student();

            Student obj2 = new Grade();

            obj1.printdetails();

            obj2.printdetails();

            Console.ReadLine();

        }

    }

}

Question 9: Access Specifier or Modifier

Answer

Object Oriented Programming enables you to restrict access of data members defined in a class so that only specific classes can access them. To specify these restrictions, C# provides you with access modifiers that allow you to specify which classes can access the data members of a specific class. The modifiers are specified using C# keywords. In C#, there are four types of access modifiers. These are:

  • Public
    The public access modifier provides the most permissive access level. The members declared as public can be accessed anywhere in the class as well as from other classes.
  • Private
    The private access modifier provides the least permissive access level. Private members are accessible only within the class in which they are declared.
  • Protected
    The protected access modifier allows the class members to be accessible within the class as well as within the derived classes.
  • Internal
    The internal access modifier allows the class members to be accessible only within the classes of the same assembly. An assembly is a file that is automatically generated by the compiler upon successful compilation of a .NET application.

Access Specifier

Question 10: Constructor and Destructor

Answer

1) Constructor

  • Definition: A Constructor initializes the values of an object and its variables and
    allocates memory for every variable and object.
  • Types of constructors: There are primarily two types of constructors, 1) Default Constructor and 2) Parameterized Constructor.
  • Rules of constructors:
  • A Constructor has the same name as its class name.
  • It can be overloaded.
  • It is called only once in the lifetime of the object.
  • It does not have any return type, not even void.
  • Can be eihter private or public.
  • Can be inherited.

2) Destructor

  • Definition: A Destructor de-initializes the values of objects and variables and releases the resources.
  • Rules of Destructors:
  • A Destructor has the same name as its class name prefixed with a tilde sign (~).
  • It cannot be overloaded.
  • It is called only once in the lifetime of the object.
  • It does not have any return type nor does it have a parameter.
  • It cannot be inherited.
  • It is never called explicitly but is always invoked implicitly.
  • It cannot be private or public.

Demo Program

namespace Constructor_Destructor1

{

    class code

    {

        public int id;

        public code()

        {

            Console.WriteLine("Hello");

        }

        public code(int a)

        {

            id = a;

        }

 

        public void printdata()

        {

            Console.WriteLine(id);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            code obj = new code();

            int a = 200;

            code obj1 = new code(a);

            Console.Write("\nID of A is:-");

            obj1.printdata();

            int b = a;

            code obj2 = new code(b);

            Console.Write("\nID of B is:-");

            obj2.printdata();

            int c = b;

            code obj3 = new code(c);

            Console.Write("\nID of C is:-");

            obj3.printdata();

            Console.ReadLine();

        }

    }

}


Question 11: Events and Delegates

Answer

  • Definition: Delegates in C# are used to reference methods defined in a class.
  • Delegates are objects that contain references to methods that need to be invoked instead of containing the actual method names.
  • Using delegates, you can call any method, that is identified only at runtime.
  • A delegate is like having a general method name that points to various methods at run-time.
  • In C#, invoking a delegate will execute the referenced method at run-time.

DELEGATES

Declaring Delegates

Delegates in C# are declared using the delegate keyword followed by the return type and the parameters of the referenced method. Declaring a delegate is quite similar to declaring a method except that there is no implementation. Thus, the declaration statement must end with a semi-colon.

Declaring-Delegates.jpg

Rules for declaring delegate

If the delegate is declared outside the class then you cannot declare another delegate with the same name in that namespace.

Rules for declaring delegate

Types Of Delegates

1. Uni-Cast (Single) Delegates.

Single cast delegates can refer to, and call only, one method.

Demo Program

namespace Delegate_Demo1

{

    public delegate int Calculation(int numone, int numtwo);

 

    class Mathematics

    {

        public static int Addition(int numone, int numtwo)

        {

            return (numone + numtwo);

        }

        public static int Substraction(int numone, int numtwo)

        {

            return (numone - numtwo);

        }

    }

    class program

    {

        static void Main(string[] args)

        {

            int valone = 25;

            int valtwo = 23;

 

            Calculation obj = new Calculation(Mathematics.Addition);

            Calculation obj1 = new Calculation(Mathematics.Substraction);

            Console.WriteLine(valone + "+" + valtwo + "=" + obj(valone, valtwo));

            Console.WriteLine(valone + "+" + valtwo + "=" + obj1(valone, valtwo));

            Console.ReadLine();

        }

    }

}


2. Multiple Delegates

More than one delegate can be defined in a program and each delegate can only refer to one method.

Demo Program
 

namespace Multiple_Delegates_Demo

{

    public delegate double CalculateArea(double val);

    public delegate double CalculateVolume(double val);

    class cube

    {

        public static double Area(double val)

        {

            return 6 * (val * val);

        }

        public static double Volume(double val)

        {

            return (val * val);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            CalculateArea obj = new CalculateArea(cube.Area);

            CalculateVolume obj2 = new CalculateVolume(cube.Volume);

            Console.WriteLine("Surface Area of Cube:-" + obj(200.32));

            Console.WriteLine("Volume of Cube:-" + obj2(20.56));

            Console.ReadLine();

        }

    }

}

3. Multicast Delegates

Multicast delegates can point to more than one method. A multicast delegate maintains a list of functions. All the functions are called when the delegate is invoked.

Demo Program

 

namespace Delegate_Demo1

{

    public delegate int Calculation(int numone, int numtwo);

 

    class Mathematics

    {

        public static int Addition(int numone, int numtwo)

        {

            return (numone + numtwo);

        }

        public static int Substraction(int numone, int numtwo)

        {

            return (numone - numtwo);

        }

    }

    class program

    {

        static void Main(string[] args)

        {

            int valone = 25;

            int valtwo = 23;

 

            Calculation obj = new Calculation(Mathematics.Addition);

            obj += new Calculation(Mathematics.Substraction);

            //Calculation obj1 = new Calculation(Mathematics.Substraction);

            Console.WriteLine(valone + "+" + valtwo + "=" + obj(valone, valtwo));

            //Console.WriteLine(valone + "+" + valtwo + "=" + obj1(valone, valtwo));

            Console.ReadLine();

        }

    }

}

Features and Benefits

Features and Benefits of Delegate

EVENTS

Definition

  • A user or the system performs some action and it is called as an event.
  • In other words, we can say that an event is either raised by the user or the system.

Events

Raising Events

  • The delegate is one of the handlers for all events. Without a delegate an event cannot be raised or executed.
  • However, before raising an event, it is important for you to create handlers and thus ensure that the event is associated with the appropriate event handler, the declared event is considered to be null.

Demo Program

namespace Event_Demo1

{

    public delegate void Display();

    class events

    {

        public event Display Print;

        public void Show()

        {

            Console.WriteLine("Wel-Come to VS.NET 2005");

            Console.WriteLine("C# is case sensetive language");

            Console.WriteLine("C# is fully object oriented programming language");

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            events obj = new events();

            obj.Print += new Display(obj.Show);

            obj.Print();

            Console.ReadLine();

        }

    }

}


Demo Program

namespace Event_Demo2

{

    public delegate void CustDetail();

    public delegate void AccountInfo();

 

    class Bank

    {

        string _custName;

        string _accountType;

        int _custID;

        int _accountNumber;

 

        public event CustDetail Customer;

        public event AccountInfo Account;

 

        public Bank()

        {

            _custID = 1001;

            _accountNumber = 90;

            _accountType = "Fixed";

            _custName = "Pratik";

        }

        public void ShowCustomerDetail()

        {

            Console.Write("Customer ID:-" + _custID);

            Console.Write("Customer Name:-" + _custName);

        }

        public void ShowCustomerAccountDetail()

        {

            Console.Write("Account Number:-" + _accountNumber);

            Console.Write("Account Number:-" + _accountType);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Bank obj = new Bank();

            obj.Customer += new CustDetail(obj.ShowCustomerDetail);

            obj.Account += new AccountInfo(obj.ShowCustomerAccountDetail);

            obj.Customer();

            obj.Account();

            Console.ReadLine();

        }

    }

}

Question 13: Field Property

Answer

  • The access modifiers are public, private, protected and internal and control the accessibility of fields and methods in C#.
    Property

  • Properties allow you to protect a field in the class by reading and writing to the field through a property declaration. Additionally, properties allow you to access private fields, that would otherwise be in-accessible.

  • Properties can validate values before allowing you to change them and also perform specified actions on those changes. Therefore, properties ensure security of private data.

  • Properties support abstraction and encapsulation by exposing only necessary actions and hiding their implementation.

  • A property declaration contains special methods to read and set private values. However, properties are accessed in a way that is similar to accessing a field. Therefore, properties are also known as smart fields.

ACCESSOR

  • There are prinmarily two types of accessors, "get" and "set" accessors.
  • Property accesors allow you to read (get) and assign a value (set).
  • The get accessor reads a value and is executed when the property name is referred to. It does not take any parameter and returns a value that is of the return type of the property.
  • The set accessor assigns a value and is executed when the property is assigned a new value using the equal to operator. This value is stored in the private field by an implicit parameter called "value" (keyword in C#) used in the set accessor.
  • A property can be declared as static using the static keyword. A static property is accessed using the class name and is available to the entire class rather than just an instance of the class. The set and get accessors of the static property can access only the static members of the class.

GET and SET ACCESSOR

Syntax

Property Syntax

Type of Property

Type of Property

Properties are broadly divided into the three categories, read-only, write-only, and read-write properties.

  1. A read-only property allows you to only retrieve the value of a private field. To create a read-only property, you should define the get accessor.
  2. A write-only property allows you to only change the value of a private field. To create a write-only property, you should define the set accessor.
  3. A read-write property allows you to set and retrieve the value of a private field. To create a read-write property, you should define the set and get accessors.

Demo Program

namespace PropertyDemo1

{

    class SalaryDetails

    {

        private string _empName;

        //Declaration of prperty

        public string EmpName

        {

            get

            {

                return _empName;

            }

            set

            {

                _empName = value;

            }

        }

        static void Main(string[] args)

        {

            SalaryDetails obj = new SalaryDetails();

            obj.EmpName = "Partik Johnson";

            Console.WriteLine("Employee Name:-" + obj.EmpName);

            Console.ReadLine();

        }

    }

}

COMMENT USING