Classes in C#.Net

A class is a blueprint, that defines the attributes and behaviors of the objects, that are created as instances of the class.

Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces. Every class has a constructor, which is called automatically any time an instance of a class is created. The purpose of constructors is to initialize class members when an instance of the class is created.

Constructors do not have return values and always have the same name as the class.

class SampleClass
{
 //----method----
}
// Namespace Declaration
using System;

// helper class
class OutputClass 
{
    string myString;

    // Constructor
    public OutputClass(string inputString) 
    {
        myString = inputString;
    }

    // Instance Method
    public void printString() 
    {
        Console.WriteLine("{0}", myString);
    }

    // Destructor
    ~OutputClass() 
    {
        // Some resource cleanup routines
    }
}

// Program start class
class ExampleClass 
{
    // Main begins program execution.
    public static void Main() 
    {
        // Instance of OutputClass
        OutputClass outCl = new OutputClass("This is printed by the output class.");

        // Call Output class' method
        outCl.printString(); 
    }
}

Types of classes in C#.Net:

  1. Abstract Class (Pure Virtual Class)
  2. Partial Class
  3. Sealed Class
  4. Static Class

Abstract Class:

The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An example of an abstract class declaration is:

abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

An example of an abstract method:

abstract class absClass
{
  public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

A sample program that explains abstract classes:

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample, we can see that the abstract class absClass contains two methods AddTwoNumbers andMultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation andMultiplyTwoNumbers is an abstract method that does not contain implementation.

Abstract classes have the following features:

  1. An abstract class cannot be instantiated.
  2. An abstract class may contain abstract methods and accessors.
  3. It is not possible to modify an abstract class with the sealed (C# Reference) modifier because the two modifers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
  4. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

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.

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace.
Some do’s and don’ts about partial class:-

  1. All the parts of a partial class must be prefixed with the keyword partial.
  2. Accessibility, signature etc. must be same in all parts of the partial class.
  3. You cannot sealed one part of the partial class. In that case entire class in sealed.
  4. If you define any part of the partial class abstract, entire class will become abstract.
  5. Inheritance cannot be applied to a part of partial class. If you do so, it applies to entire class.
  6. Nested partial types are allowed in partial-type
  7. The partial modifier is not available on delegate or enumeration declarations.
public partial class Employee
{
    public void DoWork()
    {
    }
}

public partial class Employee
{
    public void GoToLunch()
    {
    }
}

Sealed Class:

When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.

class A {}    
sealed class B : A {}
  1. A sealed class cannot be a base class.
  2. The modifier abstract cannot be applied to a sealed class.
  3. By default, struct (structure) is sealed. It is the last class in hierarchy.
  4. To access the members of a sealed class, you must create objects of that class.
  5. Sealed Class is denoted by the keyword sealed.
sealed class SealedClass
{
    public int x;
    public int y;
}

class SealedTest2
{
    static void Main()
    {
        SealedClass sc = new SealedClass();
        sc.x = 110;
        sc.y = 150;
        Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
    }
}

We can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

class X
{
    protected virtual void F() { Console.WriteLine("X.F"); }
    protected virtual void F2() { Console.WriteLine("X.F2"); }
}
class Y : X
{
    sealed protected override void F() { Console.WriteLine("Y.F"); }
    protected override void F2() { Console.WriteLine("Y.F2"); }
}
class Z : Y
{
    // Attempting to override F causes compiler error CS0239.
    // protected override void F() { Console.WriteLine("C.F"); }

    // Overriding F2 is allowed.
    protected override void F2() { Console.WriteLine("Z.F2"); }
}

Static Class:

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.

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:-

  1. A Static Class can only have static members.
  2. If the static keyword is applied to a class, all the members of the class must be static.
  3. A Static Class cannot be instantiated.
  4. A Static Class is sealed, so cannot be inherited.
  5. A Static Class cannot have a constructor (except static constructor).
  6. It is not possible to use this to reference static methods or property accessors.

Static Class is denoted by the keyword static.

// 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));

 

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply