Sunday, July 1, 2012

Achieve polymorphism in C# .NET


How to achieve polymorphism in C#.NET?


Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces.It can be achieved in the following ways.


Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class.


To completely take over a class member from a base class, the base class has to declare that member as virtual.

Use of System.Environment class in C# .NET


What is the use of System.Environment class in C#.NET?


The System.Environment class can be used to retrieve information like below :

  • Command-line arguments.
  • The exit code.
  • Environment variable settings.
  • Contents of the call stack.
  • Time since last system boot.
  • The version of the common language runtime.


Prevent class from being inherited in C#.NET


How to prevent a class from being inherited in C#.NET?


The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.


Add ReadOnly property in C#.NET?


How to add a ReadOnly property in C#.NET?


Properties can be made read-only by having only a get accessor in the implementation. For example


public class X
{
          public X(int id)
          {
               x_id = id;
          }
          public int ID
          {
              get
              {
                   return x_id;
              }
          }
}

Implementation inheritance and interface inheritance

What are implementation inheritance and interface inheritance?


Implementation inheritance is achieved when a class is derived from another class in such a way that it inherits all its members.


Interface inheritance is when a class inherits only the signatures of the functions from another class.