• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » C# Oops

What is Polymorphism in C#

By Dinesh Thakur

Method overriding means same name methods in different classes.

Polymorphism is a feature to use one name in many forms. There ·Polymorphism can be achieved in following ways in C#:

• Method Overloading
• Method Overriding
• Method Hiding

Method overloading, means multiple methods of same name with different arguments in a single class or program. Method overriding and hiding makes use of the following three method-head keywords

• new
• virtual,
• override

The main difference between hiding and overriding relates to the choice of which method to call where the declared class of a variable is different to· the run-time class of the object it references. This point is explained further below.

Method Overriding

Suppose that we define a Square class which inherits from a Rectangle class (a square being a special case of a rectangle). Each of these classes also specifies a ‘getarea’ instance method, returning the area of the given instance.

For the Square class to ‘override’ the Rectangle class’ getArea method, the Rectangle class’ method must have first declared that it is happy to be overridden. One way in which it can do this is with the ‘virtual’ keyword. So, for instance, the Rectangle class’ getArea method might be specified like this:

publicvirtualdouble getArea(){return length * width;}

To override this method the Square class would then specify the overriding method with the ‘override’ keyword. For example: 

publicoverridedouble getArea(){return length * width;}

Note that for one method to override another, the overridden method must not be static, and it must be declared as either ‘virtual’, ‘abstract’ or ‘override’. Furthermore, the access modifiers for each method must be the same.

The major implication of the specifications above is that if we construct a new Square instance and then call its ‘getArea’ method, the method actually called will be the Square instance’s getArea method. So, for instance, if we run the following code: 

square sq =new Square(S);

double area = sq.getArea();

then the getArea method called on the second line will be the method defined in the Square class.

There is, however, a more subtle point. To show this, suppose that we declare two variables in the following way:

Square sq =new square(4);

Rectangle r = sq;

Here variable r refers to sq as a Rectangle instance (possible because the Square class· derives from the Rectangle class). We can now raise the question: if we run the following code 

double area = r.getArea();

then which getArea method is actually called – the Square class method or the Rectangle class method.

The answer in this case is that the Square class method would still be called. Because the Square class’ getArea method ‘overrides’ the corresponding method in the Rectangle class, calls to this method· on a Square instance always ‘slide through’ to the overriding method.

Method Overriding

using system;

class demo {

   class A {

       publicvirtualvoid show(){

               console.writeLine(“I am A“);

       }

    }

   class B:A {

        publicoverridevoid show(){

               console.writeLine(“I am B“);

        }

    }

    class C:A {

        publicoverridevoid show(){

               console.writeLine(“I am c“);

        }

     }

        publicstaticvoid Main(){

              A o;

              o =new B();

              o.show();

              o =new c();

              o.show();

         }

}

OUTPUT:

I am B

I am c

Method hiding

Where one method ‘hides’ another, the hidden method does not need to be declared with any special keyword. Instead, the hiding method just declares itself as ‘new’, So, where the Square class hides the Rectangle class’ getArea method, the two methods might just be written thus:

publicdouble getArea()// in Rectangle {

     return length * width;

}}

publicnewdouble getArea()// in Square {

    return length.* length;

}}

Note that a method can ‘hide’ another one without the access modifiers of these methods being the same. So, for instance, the Square’s getArea method could be declared as private, viz:

Private newdouble getArea(){

      return length * length;

}

This leads us to an important point. A ‘new’ method only hides a super-class method with a scope defined by its access modifier. Specifically, where the access level of the hiding method is ‘private’, as in the method just described, this method only hides the super-class method for the particular class in which it is defined.

To make this point more concrete, suppose that we introduced a further class, SpecialSquare, which inherits from Square. Suppose further that SpecialSquare does not overwrite the getArea method. In this case, because Square’s getArea method is defined as private, SpecialSquare inherits its getArea method directly from the Rectangle class (where the getArea method is public).

The final point to note about method hiding is that method calls do not always ‘slide through’ in the way that they do with virtual methods. So, if we declare two variables thus:

Square sq =new square(4);

Rectangle r = sq;

then run the code double area = r.getArea();

the get Area method run will be that defined in the Rectangle class, class, not the Square class.

Method hiding

using System;

class demo {

    class A {

         public virtual void show() {

              console.writeLine(“1 am A”);

         }}

    class B:A {

         public new void show() {

               console.writeLine(“I am B“);

        }}

    class B:A {

        public new void show() {

               console.writeLine(“I am e“);

       }}

       public static void Main() {

           A o;

           o = new B();

           o.show();

           o = new e();

           o.show();

   }

}

OUTPUT:

I am A

I am A

Type of Inheritance in C#

By Dinesh Thakur

Inheritance is a mechanism of sharing the members among the classes. Inheritance means taking an existing class and adding functionality by deriving a new class from it. The class you start with is called the base class, and the new class you create is called the derived class. [Read more…] about Type of Inheritance in C#

Type of Constructor

By Dinesh Thakur

Constructor is method of class to allocate the memory of object and initialize the variables of class.

 

When you declare a variable of a class, a special method must be called to initialize the members of that class. This method is automatically provided for every class and it is called a constructor.

Default Constructor

Whenever you create, a new class, a constructor is automatically provided to it. This particular constructor is called the default constructor. You have the option of creating it or not. Although a constructor is created for your class, you can customize its behavior or change it tremendously.

 

A constructor holds the same name as its class and doesn’t return any value, not even void. Here is an example:

 

public class Exercise

{

public void welcome ()

{

console.writeline (“This is an Exercise”);

}

Public exercise ()

{

}

}

 

Like every method, a constructor can be equipped with a body. In this body, you can access any of the member variables (or methods(s) of the same class. When introducing classes other than the main class, we saw that, to use such a class, you can declare its variable and allocate memory using the new operator. You can notice that we always included the parentheses when declaring such a variable. Here is an example:

 

public class class!

{

static void Main()

{

Exercise exo = new Exercise();

}

}

In this case, the parentheses indicate that we are calling the default constructor to instantiate the class.

Consider the following Example:

 

The demonstration of constructor.

 

using System;

public class Exercise

{

public void welcome()

{

console.writeLine(“The wonderful world of c# programming”);

}

console.writeLine(“The Exercise class is now available”);

public Exercise()

{

}

}

public class class! r

t

static void Main()

{

Exercise exo = new Exercise();

}

}

 

OUTPUT:

 

The Exercise class is now available

This shows that, when a class has been instantiated, its constructor is the first method to be called. For this reason, you can use a constructor to initialize a class, that is, to assign default values to its member variables. When a constructor is used to initialize a variable declared for a class. That constructor is referred to as an instance constructor.

Parameterized Constructor

We saw that there is always a default constructor for a new class that you create; you just the option of explicitly creating one or not. The default constructor as we saw it doesn’t take arguments: this is not a rule, it is simply assumed. Instead of a default constructor, you may want to create a constructor that takes argument. Here is an example:

 

public class Quadrilateral

{

public Quadrilateral(double side)

{

}

}

With this type of constructor, when you declare an instance of the class, you can use this new constructor to initialize the class. Here is an example:

 

using System;

public class Quadrilateral

{

public Quadrilateral(double side)

{

}

}

public class classl

{

static void Main()

{

Quadrilateral Square = new Quadrilateral(6.55);

}

}

If you create one constructor for your class and pass at least one argument to that constructor, the automatic default constructor created by the compiler disappears. This implies that if you declare an instance of the class and use the default constructor to initialize it, you would receive an error when you compile the program. Based on this rule, the following program will not compile:

 

using System;

public class Quadrilateral

{

public Quadrilateral(double side) {

}

}

public class Classl

{

static void Main()

{

Quadrilateral Square = new Quadrilateral();

}

}

If you still want to use the default constructor in a class after creating a constructor that takes at least one argument, you must explicitly create that default constructor.

Private Constructor

A private constructor is a special instance (default) constructor. It is commonly used in class that contain static members only, if a class has one or more private constructors and no blic constructors, then other classes (except nested ‘classes) are not allowed to create instances of this class. For example-

Class NLog

{

II private constructor

private NLog() { }

 

public static double e = 2.71828;

}

The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don’t use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

Private constructors are useful to prevent creation of a class when these are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.

The following is an example of a class using a private constructor.

 

using System;

public class Myclass

{

private Myclass() {}

public static int counter;

public static int InerementCounter()

{

return ++counter;

}

}

 

 

class MainClass

{

static void Main ()

{

II if you uncomment the following statement, it will generate

II an error because the constructor is inaccessible

II Myclass myobject = new Myclass(); //error

Myclass.counter = 100;

Myclass.lncrementcounter();

Console.wr;teL;ne (“New count: {O}”, Myclass.counter);

}

}

 

OUTPUT:

 

New count : 100

Notice that is you uncoment the following statement from the example, it will generate

an error because the constructor is in assessable due to its protection level : /I Myclass Myobject

= new MyClass 0;// error.

Static Constructor

Like the above described instance constructors, a static constructor is used to initialize a class. The main difference is that a static constructor works internally, in the class. Therefore, it is not used to initialize a variable of the class and you can never declare a variable of a class using a static constructor.

To make a constructor static, when creating it, type the static keyword to its left. Here is an example:

 

using system;

public class Quadrilateral

{

static Quadrilateral()

{

}

}

public class class1

{

static void Main()

{

/* use the default constructor to initialize an

instance of the class */

Quadrilateral Square = new Quadrilateral

}

}

In the above class, a static constructor is created for the class but the default constructor is still available and it is used to instantiate the class. Notice· that. static constructors are not inherited, and cannot be called .directly.

After the class loader loads a class that will soon be used, but before it continues normal execution, it executes the static constructor for that class. Because of this process, you are guaranteed that classes are always initialized before they are used. The exact timing of atic constructor execution is implementation-dependent, but is subject to the following rules:

• The static constructor for a class is executed before any instance of the class is created.

• The static constructor for a class is executed before any static members of the class are referenced.

• The static constructor for a class executes at most one time during a single program instantiation.

Static Field Initializations

The most common use for a static constructor is to initialize the static fields of a .class. This is because when you initialize a static field directly at its point of declaration, the compiler conceptually converts the initialization into an assignment inside the static constructor. In other words:

 

class Example

{

private static wibble w = new wibble( };

}

is effectively converted by the compiler into

 

class Example

{

static Example( )

{

w = new wibble( );

}

private static wibble w;

}

Static Constructor Restrictions

Understanding the following four restrictions on the syntax of static constructors will help you understand how the common language runtime uses static constructors:

• You cannot call a static constructor.

• You cannot declare a static constructor with an access modifier.

• You cannot declare a static constructor with parameters.

• You cannot use this keyword in a static constructor.

Constructor Overloading

A constructor is the primary method of a class. It allows the programmer to initialize a variable of a class when the class is instantiated. A constructor that plays this role of initializing an instance of a class is also called an instance constructor. Most of the time, you don’t even need to create a constructor, since one is automatically provided to any class you create. Sometimes too, as we have seen in some classes, you need to create your own class as you judge it necessary. And sometimes, a single constructor may not be sufficient. For example, when creating a class, you may decide, or find out, that there must be more than one way for a user to initialize a variable.

Like any other method, a constructor can be overloaded. In other words, you can create a class and give it more than one constructor. The same rules used on overloading regular methods also apply to constructors: the different constructors must have different number of arguments or a different type of arguments.

Constructor overloading

 

using·system;

public class Applicant

{

public string FullName;

public string Address;

public string City;

public string State;

public string zIPcode;

public string sex;

public string DateofBirth;

public int weight;

public string Height;

public int Race;

 

II The default constructor, used to initialize an

II Applicant instance without much information

public Applicant()

{

this.FullName = “unknown”;

this.sex = “ungenerated”;

}

II A constructor that ;s passed only one argument public Applicant(string n)

{

this.FullName = n;

}

 

II A constructor with more than one argument

II This type is suitable to completely initialize a variable public Applicant(string n, string s, string dob)

{

this.FullName = n;

this. Sex = s;

this.dateofBirth = dob;

}

}

Public class exercise

{

Static applicant registerpersonalinformation()

{

string name;

char sex;

string gender = null;

string dob;

 

console.writeLine(” ** Motor vehicle Administration **”);

console.writeLine(“Applicant”s Registration”);

console.write(“Full Name: “);

name = console.ReadLine();

do

{

console.write(“sex(F=Female/M=Male): “);

sex = char.parse(console.ReadLine());

 

if( (sex != If’) && (sex != ‘F’) && (sex != ‘m’)

&& (sex != ‘M’) )

console.writeLine(“please enter a valid character”);

}while( (sex != If’) && (sex != ‘F’) &&

(sex != ‘m’) && (sex != ‘M’) );

if( (sex == If’) I I sex == ‘F’ )

gender = “Female”;

else if( (sex == ‘m’) I I (sex == ‘M’) )

gender = “Male”;

console.write(“date of Birth(mm/dd/yyyy): “);

dob = console.ReadLine();

Applicant person = new Applicant(name, gender, dob);

return person;

}

static void ShOW(Applicant person)

{

console.writeLine (“\n ** Motor vehicle Administration **”);

console.writeLine (” – Applicant’s personal Information -“);

 

console.writeLine(“Full Name: {0}”, person.FullName);

console.writeLine(“Sex: {0}”, person.sex);

console.writeLine(“Date of Birth: {0}\n”, person.DateOfBirth);

}

public static int Main()

{

Applicant App = new Applicant();

App = RegisterPersonalInformation();

ShOW(App);

return 0;

}

}

 

OUTPUT:

 

** Motor Vehicle Administration **

Applicant’s Registration

Full Name: S.K. Kataria

Sex(F=Female/M=Male): d

Please enter a valid character

Sex(F=Female/M=Male): M

Date of Birth(mm/dd/yyyy): 06/10/1972

 

** Motor Vehicle Administration **

 

– Applicant’s Personal Information —

Full Name: Dominique Monay

Sex: Male

Date of Birth: 06/10/1972

Destructor

Destructor is just opposite to the constructor, it destruct the memory of object allocated by constructor.

While a constructor is a method used to initialize an instance of a class, a destructor is used to destruct an instance of class when that variable is not used anymore. Like the constructor, the destructor has the same name as the class. To indicate that the method is a destructor, its name is preceded with a tilde symbol.

 

• A class can only have one destructor.

• Destructors cannot be inherited or overloaded.

• Destructors cannot be called. They are invoked automatically.

Here is an example of a destructor in a class:

 

Sample of destructor

 

using System;

class sampleclass

{

II Constructor

public sampleclass()

{

console.writeLine(“sampleclass – Constructor”);

}

~sampleClass()

{

console.writeLine(“Destructor of sampleclass”);

}

}

public class Newproject

{

static void Main()

{

sampleclass sample = new sampleClass();

console.writeLine(“welcome”);

}

}

 

OUTPUT:

 

SampleClass-Constructor

Welcome

Destructor of SampleClass

 

Like a (default) constructor, a destructor is automatically created for your class but you can also create it if you want. A class can have only one destructor. If you don’t create it, the compiler would create it for your class. If you create it, the compiler would not create another. A destructor cannot have an access level. A destructor is called when the memory that a class was used is no longer needed. This is done automatically by the compiler. For this reason, you will hardly need to create a destructor, since its job is automatically taken care of behind .the scenes by the compiler.

Classes and Object in C#

By Dinesh Thakur

One can create new reference types by defining classes. Classes provide templates’ from which these direct instances are generated. Where we appeal to the relation between a class and its corresponding reference type instances we shall say that a class specifies the type (also that the class specifies the constitutive elements of the type)

 

Any type is made up of elements, which we term type members. There are two main kinds of type members that a class can specify. Firstly, a class can specify other types- both value and reference. This idea, that types can contain other types, is known within the literature on object orientation as ‘containment’, or else ‘aggregation’. Where a type contains another reference type, we shall call it the containing type of the latter.

The second, main kind· of type members that a class can specify are methods, functions designed for reading and manipulating the value and reference types an instance contains.

                           The second, main kind of type members that a class can specify are methods, functions designed for reading and manipulating the value and reference types an instance contains.

Objects in C# are created from types, just like a variable. This type of an object is known as class. we can use class definition to instantiate objects, which means to create a real named instance of a class.

Declaration of Classes

Class is an user-defined data type. To create a class, you start with the class keyword followed by a name and its body delimited by curly brackets. The following is an example of a very simple class declaration

 

class classname

{

// class-body

}

The class-body contains the member data and member function of the class. C++ programmer must note that there is no semicolon after the closing brace of the class.

Members of Class

Class is a mechanism to implement the encapsulation, it bind the data and a function in a single unit. Therefore data and functions are the members of class, which is known as member data and member function.

There is an example of full class:

 

class circle

{

double radius;

public void get_radius(double r)

{

radius = r;

}

public double area()

{

return ( 3.14 * r * r);

}

}

Member Access Modifiers

Access modifiers provide the accessibility control for the members of classes to outside the class. They also provide the concept of data hiding. There are five member access modifiers provided by the C# Language.

                              Access modifiers provide the accessibility control for the members of classes to outside the class.

By default all members of class have private accessibility. If we want a member to have any other accessibility, then we must specify a suitable access modifier to it individually.

For Example:

class Demo

{

public int a;

interna1 int x;

protected double d;

float m; // private by default

}

We cannot declare more than one member data or member function under an accessibility modifier.

Read Only Member

When creating a member variable of a class, one of the decisions you make consists of deciding how the field would get its value(s). Sometimes you will allow the clients of the class to change the values of the field. In some other cases, you may want the field to only hold or present the value without being able to change it. This can still allow the clients to access the field and its value but on a read-only basis.

To create a field whose value can only be read, precede its data type, during declaration, – with the readonly keyword. Here is an example:

 

Public readonly double PI;

After declaring the variable, you should initialize it. You have two main alternatives. You can initialize the field when declaring it. Here is an example:

The use of read only members.

 

using System;

namespace Geometry

{

class circle

{

public double Radius;

public circle(double rad)

{

Radius = rad;

}  

Public readonly double pi = 3.14159

}

class Exercise

{

static int Main()

{

Circle circ = new Circle(24.72);

Console.writeline(“circle characteristics”);

Console.writeline(“radius: {0}”, circ.radius);

Console.writeline(“pi: {0}\n”,circ.pi);

Return 0;

}

}

}

OUTPUT:

 

circle Characteristics

Radius: 24.72

PI: 3.14159

Object creation

In C# objects are created using the new keyword. Actually new is an operator, creates an object of the specified class and returns a reference to that object. Here is an example :

 

public class Exercise

{

public void welcome()

{

Console.writeLine(“This is Exercise class”);

}

}

public class classl

{

static void Main()

{

Exercise exo = new Exercise ();

}

Object-Oriented programming in C#

By Dinesh Thakur

Object-Oriented programming emphasis on data rather than function.

Object-Oriented programming was developed due to the limitations of the traditional programming approaches. The traditional programming approaches, such as Pascal, C, BASIC, FORTRAN and etc., are basically called procedural-oriented programming languages.

Procedural-oriented programming basically emphasis on writing a list of instructions to tell the computer to do something: Get some input, add these numbers, divide by 6, display that output. The programs are dividend into a small subprogram know as a function. Most of functions share global data, if program is too large it is very difficult to identify what data is used by which function. It does not model real world problem, and new enhancement is not easy, whole will be changed or new will be develop.

Object-Oriented Programming emphasis on data rather than function. It divides programs into objects, and they can communicate with each other. It provides the concept to hide the data from the external function and program. New data and functions can be easily added rever necessary. Some fundamental features of Object-Oriented programming are:

.” Concept

Elements of Object-Oriented programming

 

» Member data

A member data is a data hold by an entity (or object).

» Methods

A method is an operation on the member data. Also known as member function.

» Objects

An Object is a real world entity, combine the data and member function in a single unit.

» Classes

Class is a set of similar types of objects.

 

Characteristics of Object-Oriented Programming

 

» Encapsulation

Encapsulation is a mechanism of binding the member data and member function in a single unit.

» Data Abstraction

Data abstraction is mechanism to provide the. Essential feature without describing the background details. Means providing the func1ions to access the hidden (private) data.

» Inheritance

Inheritance is a mechanism of sharing the member data and member function among the classes.

» Polymorphism

Polymorphism is a property to share a single item (or name) in more than one form. (such as function overloading, operator overloading, virtual functions)

Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW