Different types of Classes in C# .Net - With Definition and Examples


In this article, I'll explain different types of classes in C# .Net (Microsoft Tecnologies). I'll also give examples for each of the classes. It'll be useful for beginners and a good resource for interview preparation. To have a fare understanding of classes is always good for interviews and programming as well.

Classes in C#.Net


Types of classes in C#.Net:


• Abstract Class (somtimes called a Pure Virtual Class)

• Partial Class

• Sealed Class

• Static Class

Abstract Class:


An Abstract Class means that, no object of this class can be instantiated, but can make derivation of this. It can serve the purpose of base class only as no object of this class can be created.
Abstract Class is denoted by the keyword abstract.

Example:



abstract class myClass
{
public myClass()
{
// code to initialize the class…
}

abstract public void anyMethod_01();
abstract public void anyMethod_02(int anyVariable);
abstract public int anyMethod_03 (int anyvariable);
}

It is important here to note that abstract classes can have non-abstract method(s), even can have only non-abstract method(s).


abstract class myclass
{
public void nonAbstractMethod ()
{
// code…
}
}

… is perfectly alright.
An abstract class can be derived from another abstract class. In that case, in the derived class, it is optional to implement the abstract method(s) of the base class.

Example:



// Base abstract class
abstract class baseClass
{
public abstract int addNumbers (int a, int b);
public abstract int multiplyNumbers(int a, int b);
}

// Derived abstract class
abstract class derivedClass:baseClass
{
// implementing addNumbers…
public override int addnumbers (int a, int b)
{
return a+b;
}
}

// Derived class from 2nd class (derivedClass)
class anyClass: derivedClass
{
// implementing multiplyNumbers of baseClass…
public override int multiplyNumbers(int a, int b)
{
return a*b;
}
}

In the above example, we only implemented addNumbers in the derived abstract class (derivedClass). The abstract method multiplyNumbers is implemented in the anyClass, which is in turn derived from derivedClass.

Partial Class:


This special type of class called "Partial Class" is introduced with .Net Framework 2.0. Partial Class allows its members – method, properties, and events – to be divided into multiple source files (.cs). At compile time these files get combined into a single class.
Partial Class is denoted by the keyword partial.
Some do's and don'ts about partial class:-
• All the parts of a partial class must be prefixed with the keyword partial.
• Accessibility, signature etc. must be same in all parts of the partial class.
• You cannot sealed one part of the partial class. In that case entire class in sealed.
• If you define any part of the partial class abstract, entire class will become abstract.
• Inheritance cannot be applied to a part of partial class. If you do so, it applies to entire class.

Example:



public partial class myPartialClass
{
public void firstMethod()
{
// code…
}
}

public partial class myPartialClass
{
public void secondMethod()
{
// code…
}
}


Sealed Class:


A sealed class is a class which cannot be inherited. A sealed class cannot be a base class. The modifier abstract cannot be applied to a sealed class. By default, struct (structure) is sealed. It is the last class in hierarchy. To access the members of a sealed class, you must create objects of that class.
Sealed Class is denoted by the keyword sealed.

Example:



sealed class mySealedClass
{
int a;
int b;
}

Class mainClass
{
public static void Main()
{
mySealedClass obj = new mySealedClass();
obj.a = 5;
obj.b = 7;
Console.WriteLine("a = {0}, b = {1}", obj.a, obj.b);
}
}

Static Class:


A Static Class is one which cannot be instantiated. The keyword new cannot be used with static classes as members of such class can be called directly by using the class name itself.
Following are the main characteristics of a static class:-
• A Static Class can only have static members.
• A Static Class cannot be instantiated.
• A Static Class is sealed, so cannot be inherited.
• A Static Class cannot have a constructor (except static constructor).
Static Class is denoted by the keyword static.

Example:



// static class definition…
public static class myclass
{
public static int addNumbers(int a, int b)
{
return (a + b);
}
}

// to use it, we call directly on the class…
Console.WriteLine("The addition of 5 and 7 is: " + myClass.addNumbers(5, 7));

All the best... !!!


Comments

Author: satyajee srivastava26 Jun 2012 Member Level: Silver   Points : 0

Good Works.Keep Posting

Author: Ajesh Madhukar Dalvi13 Aug 2012 Member Level: Silver   Points : 5

here are Partial,abstract,static,sealed and instance classes in c#.
Partial Class: Partial class is useful when the class functionality is too big (i.e when number of lines of code in the class is too big) and when a developer want to share some of the functionalities with other developers this is useful.
Description
In the following example, the fields and the constructor of the class, CoOrds, are declared in one partial class definition, and the member, PrintCoOrds, is declared in another partial class definition.
Code
C#

public partial class CoOrds
{
private int x;
private int y;

public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
}

public partial class CoOrds
{
public void PrintCoOrds()
{
Console.WriteLine("CoOrds: {0},{1}", x, y);
}

}

class TestCoOrds
{
static void Main()
{
CoOrds myCoOrds = new CoOrds(10, 15);
myCoOrds.PrintCoOrds();

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: CoOrds: 10,15



Sealed Class : when the class is functionality is complete and you don’t want to allow any other class to extend your class,then you need to declare your class as sealed. No other Class can extend or use your sealed class as base class.
Example
// cs_sealed_keyword.cs
// Sealed classes
using System;
sealed class MyClass
{
public int x;
public int y;
}

class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Output
x = 110, y = 150


Abstract Class: When the developer/programmer don’t know the functionality of the class fully and , you want to leave the implementation to the derived classes , then use the Abstract class. In the abstract class you can have 0 or more abstract methods,properties and along with implemented methods. You cannot create an instance to the Abstract Class.And also if you have family of related classes and all those classes having some common functionality try pushing then into a common base class. this way you will get code re-usability and can get easy maintainability.
Example
In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().
// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

public abstract int GetX // Abstract property
{
get;
}

public abstract int GetY // Abstract property
{
get;
}
}

class MyDerivedC: MyBaseC
{
public override void MyMethod()
{
x++;
y++;
}

public override int GetX // overriding property
{
get
{
return x+10;
}
}

public override int GetY // overriding property
{
get
{
return y+10;
}
}

public static void Main()
{
MyDerivedC mC = new MyDerivedC();
mC.MyMethod();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);
}
}
Output
x = 111, y = 161

Static Class: when any class is most frequently used or if any class is qualified as helper class( helper class is one which will be repeatedly used by all other classes) then try using Static Class. Advantage with static class is “Object instantiation overhead is reduced”.And this class always have single memory location where in every other class will hit the same memory location. If class A changed some data in static class , Changed data is available to every other subsequent classes who access the static class.
Example
This example reads the name and ID of a new employee, increments the employee counter by one, and displays the information for the new employee as well as the new number of employees. For simplicity, this program reads the current number of employees from the keyboard. In a real application, this information should be read from a file.
// cs_static_keyword.cs
// Static members
using System;
public class Employee
{
public string id;
public string name;

public Employee ()
{
}

public Employee (string name, string id)
{
this.name = name;
this.id = id;
}

public static int employeeCounter;

public static int AddEmployee()
{
return ++employeeCounter;
}
}

class MainClass: Employee
{
public static void Main()
{
Console.Write("Enter the employee's name: ");
string name = Console.ReadLine();
Console.Write("Enter the employee's ID: ");
string id = Console.ReadLine();
// Create the employee object:
Employee e = new Employee (name, id);
Console.Write("Enter the current number of employees: ");
string n = Console.ReadLine();
Employee.employeeCounter = Int32.Parse(n);
Employee.AddEmployee();
// Display the new information:
Console.WriteLine("Name: {0}", e.name);
Console.WriteLine("ID: {0}", e.id);
Console.WriteLine("New Number of Employees: {0}",
Employee.employeeCounter);
}
}
Input
Tara Strahan
AF643G
15

Author: koti Balaji25 Jul 2013 Member Level: Silver   Points : 8

Abstract class


We cannot create object for abstract class

Abstract method should not contain method body {}

If abstract method
public abstract void Multiply(int Num1, int Num2);
receive 2 arguments then
all overridden method should receive 2arguments

This rule apply for virtual method also,
If virtual method has 2 arg all overridden
method should have 2argument



Example of abstract class

using System;
namespace ConsoleApplication37
{

public abstract class car
{
public abstract void displayMsg();
// no method body in abstract method

}

// we can declare any constructor,destr,without
method body,
// no method body {} is allowed in abstract method

// if abstract method or virtual method receive argument then all the override methods will have same argument

class indica : car
{

public override void displayMsg()
{
Console.WriteLine("You are dealing with Indica Car");
}
}

class Toyota : car
{
public override void displayMsg()
{
Console.WriteLine("You are dealing with Toyota Car");
}
}

class vista : car
{
public override void displayMsg()
{
Console.WriteLine("You are dealing with vista Car");

}
}
class test
{
public static void Main()
{
indica obj1 = new indica();
// obj cannot be created for abstract class
obj1.displayMsg();
Toyota obj2 = new Toyota();
obj2.displayMsg();
vista obj3 = new vista();
obj3.displayMsg();

} }
}


Output

You are dealing with Indica Car

You are dealing with Toyota car

You are dealing with vista Car

Author: koti Balaji25 Jul 2013 Member Level: Silver   Points : 7

Virtual function

Virtual method (or) function gives option to its derived classes
i.e invoke their own methods or virtual method will invoked automatically

namespace ConsoleApplication36
{
class Base
{
public virtual void method1()
{
Console.WriteLine(" method1 of BaseClass");

}
public virtual void method2() //virtual gives choice
{
Console.WriteLine(" method2 of BaseClass");

}
}


class derived : Base
{
public override void method1()
{
Console.WriteLine(" method 1 of derived");
}
public override void method2()
{
Console.WriteLine(" method 2 of derived");
}
}


class derived1 :Base
{
//if class derived1 : derived
// if it is from derived then method1of derived isexecuted

public override void method2()
{
Console.WriteLine(" method 2 of derived 1 ");
}
}

class testClass
{
public static void Main()

{
derived obj = new derived ();
derived1 obj1 = new derived1();
obj.method1();
obj.method2();
obj1.method1();
obj1.method2();
}
}}

Output

method1 of derived

method2 of derived

method1 of Baseclass

method2 of derived1



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: