Showing posts with label OOPS. Show all posts
Showing posts with label OOPS. Show all posts

Polymorphism in C#

Polymorphism is the ability of an object oriented language (C# in this context) to allow a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendents. A class’s polymorphic interface is constructed using any number of virtual or abstract members.

A virtual member is a member in a base class that defines a default implementation that may be changed (overridden) by a derived class.

In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type.

In either case (virtual or abstract), when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.

Method Overriding – Method Overriding is a process in which a derived class can define its own version of a method, which was originally defined by its base class.

Virtual Keyword – The virtual keyword indicates that the base class wants to define a method which may be (but does not have to be) overridden by a derived class. A virtual method provides a default implementation that all derived types automatically inherit. If a child class so chooses, it may override the method but does not have to.

Note: Subclasses are never required to override virtual methods.

Override Keyword – The override keyword is used by a derived class to to change the implementation details of a virtual method (defined in the base class). Each overridden method is free to leverage the default behavior of the parent class using the base keyword.

Sealed Keyword – The sealed keyword is basically applied to classes to prevent other types from extending its behavior via inheritance.

It can also be applied to virtual methods to prevent derived types from overriding those methods. Ex.

public override sealed void GiveBonus(float amount)
{
...
}

Any effort to override the above sealed method in the derived class will generate compile time error.

Abstract Classes – The abstract keyword can be used in the class definition to prevent direct creation of an instance of the class. Although abstract classes cannot be created directly, it is still assembled in memory when derived classes are created. Thus, it is perfectly fine for abstract classes to define any number of constructors that are called indirectly when derived classes are allocated.

An abstract class can define any number of abstract members (members that does not supply a default implementation, but must be accounted for by each derived class).

The polymorphic interface of an abstract base class simply refers to its set of virtual and abstract methods. Methods marked with abstract are pure protocol. They simply define the name, return type (if any), and parameter set (if required).

If you do not override an abstract method (of the base abstract class) in the derived class, the derived class will also be considered abstract, and would have to be marked abstract with the abstract keyword.

Although it is not possible to directly create an instance of an abstract base class, you can freely store references to any subclass with an abstract base variable.

Q: What is an efficient way to force each child class to override a virtual method?

A: To force each child class to override a virtual method, we can better define an abstract method (which by definition means you provide no default implementation whatsoever), in an abstract class.

Inheritance in C#

Inheritance is the ability of an object oriented language (C# in this context) to build new class definitions based on existing class definitions. Inheritance allows us to extend the behavior of a base (parent) class by inheriting core functionality into the derived subclass (child class). Inheritance promotes code re-usability.

Inheritance preserves encapsulation – private members of the base class can never be accessed from an object reference of the derived class. Private members can only be accessed by the class that defines it.

C# does not support Multiple Inheritance. A class in C# cannot directly derive from two or more base classes.

What is Black Box programming?

A well-encapsulated class should protect its data and hide the details of how it operates from the outside world. This is often termed Black Box programming.

The beauty of this approach is that an object is free to change how a given method is implemented under the hood. It does this without breaking any existing code making use of it, provided that the parameters and return values of the method remain constant.

The notion of Black Box programming is very closely related to the concept of Encapsulation.

Encapsulation in C#

Encapsulation is the ability of an object oriented language (C# in this context) to hide unnecessary implementation details from the object user. Encapsulation makes coding simpler and helps to preserve data integrity.

According to the concept of encapsulation, an object’s internal data should not be directly accessible from an object instance. Members of a class that represent an object’s state should not be marked as public. The state of an object should only be altered indirectly by using public members. C# prefers properties to encapsulate data. Ex.

class ABC
{
// private data members
private int roll;
private int class;
private string name;

// public properties
public int Roll
{
get { return roll; }
set { roll = value; }
}
public int Class
{
get { return class; }
set { class = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}

// constructor
public ABC()
{
// values are assigned to data members via properties
Roll = 10;
Class = 9;
Name = “Rajveer Raj Banti”;
}
}

Static Constructors - What is the output of the C# code?

class A
{
  public A(string text)
  {
    Console.WriteLine(text);
  }
}

class B
{
  static A a1 = new A("a1");

  A a2 = new A("a2");

  static B()
  {
    a1 = new A("a3");
  }

  public B()
  {
    a2 = new A("a4");
  }
}

class Program
{
  static void Main(string[] args)
  {
    B b = new B();
  }

}

Before any code of the type B gets executed, its static constructor will be invoked first. It initializes static data fields and then executes statements inside the static constructor. Therefore, it prints a line of “a1”, and then another line of “a3”.

When the execution flow reaches the statement B b = new B(), the ordinary constructor is invoked. It initializes its data fields first and then the statements in its constructor method, so it prints a line of “a2”, and then another line of “a4”.

Output:

a1
a3
a2
a4

Explain Classes in detail

A class is the blueprint from which individual objects are created. This blueprint describes the state and behaviour that all the objects of the class share.  A class may be composed of any number of members (such as properties, methods, and events) and data fields. A class has both an interface and a structure.

Concrete classes


A concrete class is a class that can be instantiated.

Abstract Classes


Abstract classes are intended to define common behaviours for derived types. An abstract class is designed only as a parent class from which child classes may be derived. Abstract classes cannot be instantiated. They are often used to represent abstract concepts or entities. The incomplete features of the abstract class are then shared by a group of subclasses which add different variations of the missing pieces. The behaviours defined by such a class are "generic" and much of the class will be undefined and unimplemented. Before a class derived from an abstract class can become concrete, it must implement all of the abstract methods in parent classes.

Abstract Method


An abstract method contains no body and is, therefore, not implemented by the base class. Thus, a derived class must override it. An abstract method is automatically virtual, and it is an error to use virtual and abstract together. The abstract modifier can only be used on normal methods. It cannot be applied to static methods. Properties and indexers can also be abstract.

When a derived class inherits an abstract class, it must implement all of the abstract methods in the base class. If it doesn't  then the derived class must also be specified as abstract. Thus, the abstract attribute is inherited until such time that a complete implementation is achieved.                                                                                              

Sealed classes


A sealed class cannot be used as a base class. For this reason, it also cannot be an abstract class. Sealed classes are primarily used to prevent derivation. They add another level of strictness during compile-time, improve memory usage, and trigger certain optimizations that improve run-time efficiency.  

Partial classes 


The partial keyword allows the class, struct, method or interface to span across multiple files. Partial classes are classes that can be split over multiple definitions (typically over multiple files), making it easier to deal with large quantities of code. At compile time the partial classes are grouped together, thus logically make no difference to the output. A primary benefit of partial classes is allowing different programmers to work on different parts of the same class at the same time. They also make automatically generated code easier to interpret, as it is separated from other code into a partial class. 

Static Classes      


When a class is defined as static, it cannot be instantiated using the new keyword, and it can contain only static members or fields. 

Static classes are used to create data and functions that can be accessed without creating an instance of the class. Static classes can be used when there is no data or behavior in the class that depends on object identity.

It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework Common Language Runtime (CLR) when the program or namespace containing the class is loaded


Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state. The System.Console and System.Math classes are good examples of static classes.
The main features of static classes are: 

  • They only contain static members.
  • They cannot be instantiated. 
  •  They are sealed.
  • They cannot contain Instance Constructors.

Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.

Static methods can be overloaded but not overridden. A field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).

Differentiate between an Interface and an Abstract class


Interface:

  • Interfaces are closely related to abstract classes that have all members abstract.
  • All the methods of an interface must be virtual.
  • A Class that implements an interface must provide concrete implementation of all the methods definition in an interface or else must be declared an abstract class.
  • In C#, multiple inheritance is possible only through implementation of multiple interfaces.
  •  An interface defines a contract and can only contains four entities viz methods, properties, events and indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.
  • Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.
  • Class members that implement the interface members must be publicly accessible.
  • Interface increase security by hiding the implementation.

Abstract Class:

  • At least one method of an abstract class must be an abstract method that means it may have concrete methods.
  • Abstract class’s methods can’t have implementation only when declared abstract, otherwise they can have implementations and they have to be extended.
  • Abstract class can implement more than one interfaces, but can inherit only one class.
  • Abstract classes can only be derived once.
  • Abstract class must override all abstract method and may override virtual methods.
  • Abstract class can be used when implementing framework
  • Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.

What is an Interface?


An interface provides a specification rather than an implementation for its members. The members of interface will be implemented by the classes and structs that implement the interface. An interface can contain only methods, properties, events, and indexers (an abstract class also precisely contains the same members). An interface is special in the following ways:
  • Interface members are all implicitly abstract. In contrast, a class can provide both abstract members and concrete members with implementations.
  • A class (or struct) can implement multiple interfaces. In contrast, a class can inherit from only a single class, and a struct cannot inherit at all.
Interface members are always implicitly public and cannot declare an access modifier. Implementing an interface means providing a public implementation for all its members:

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.

interface ISum
{
 
int iGetSum(int i, int j); //By Default Public
}

class Sum : ISum
{
  public int iGetSum(int i, int j) //Must be declare Public
 {
   return i + j;
 }
}

Overloading and Overriding: What is the difference?

Overloading and overriding are different aspects of polymorphism.


Overloading is when you define two methods with the same name in the same class but with different signatures. Signature includes method name and parameters. These functions can be part of base class or derived class. Overloading is resolved at compile time.
Overloading is also called static/early binding polymorphism. Overloading is compile time binding.

Overriding is when you redefine a method that has already been defined in a parent class with their same signature. We can override a function in base class by creating a similar function in derived class and by use virtual/override keywords. 
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword. 
Derived class method will completely override base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
Overriding is mostly resolved at runtime, depending on language and situation. C++ and C# for example, are tricky in this respect, as methods are by default not overridable at runtime, but compile time (the virtual keyword controls this behavior). The C# compiler will however issue warnings when it suspects you have got it wrong.
Overriding is also called dynamic/late binding polymorphism. Overriding is runtime binding. 

Example:

Base Class:
-------------------------------
public class BaseClass
{
  public virtual void Method1()
  {
    Print("Base Class Method");
  }
}

Derived class
-----------------------------

public class DerivedClass: BaseClass
{
  public override void Method1()
  {
    Print("Derived Class Method");
  }
}

Usage
--------------------------
public class Sample
{
  public void TestMethod()
  {
    DerivedClass objDC = new DerivedClass();
    objDC.Method1();
    BaseClass objBC = (BaseClass)objDC;
    objDC.Method1();
  }
}


Result
---------------------
Derived Class Method
Derived Class Method

Difference between class and struct in C# .Net

1. Classes are reference types and structs are value types. Since classes are reference type, a class variable can be assigned null. But we cannot assign null to a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap. When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object (instance) of a class. But you will not be dealing with references to an instance of a struct (but dealing directly with them).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs, but classes can have.
Example:
class MyClass
{
int iVar = 10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int iVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors, but structs cannot have an explicit declaration of a parameter less constructor. A struct always has a built-in public default constructor. This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
7. A structs static constructor is not triggered by calling the structs default constructor. It is for a class.
8. Classes support inheritance. But there is no inheritance for structs (structs don’t support inheritance, polymorphism).
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.


11. A class is permitted to declare a destructor, but a struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.
12. Classes are used for complex and large set data. structs are simple to use.

Difference between class and interface in C#

A C# Class Considered being the primary building block of the language. What I mean by the primary building block of the language is that every time you work with C# you will create Classes to form a program. We use Classes as a template to put the properties and functionalities or behaviors in one building block for some group of objects and after that we use that template to create the objects we need.

A class can contain declarations of the following members:

Constructors, Destructors, Constants, Fields, Methods, Properties,Indexers, Operators, Events, Delegates, Classes, Interfaces, Structs

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list.


interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

Differentiate between Shadowing and Overriding

Shadowing – This is a VB.Net concept by which you can provide a new implementation for the base class member without overriding the member. You can shadow a base class member in the derived class by using the keyword Shadows. The method signature, access level and return type of the shadowed member can be completely different than the base class member.

Hiding – This is a C# concept by which you can provide a new implementation for the base class member without overriding the member. You can hide a base class member in the derived class by using the keyword new. The method signature, access level and return type of the hidden member has to be same as the base class member.

Comparision of Shadowing, Hiding and Overriding
  1. The access level, signature and the return type can only be changed when you are shadowing with VB.NET. Hiding and overriding demands that these parameters are same.
  2. The difference lies when you call the derived class object with a base class variable. In case of overriding although you assign a derived class object to base class variable it will call the derived class function.
    In case of shadowing or hiding the base class function will be called.

There are two main Differences between Shadowing and Overriding
  1. Overriding redefines only the implementation but shadowing redefines the whole Element.
  2. In Overriding (VB.NET), the Derived class can refer the Base class using Me keyword but in shadowing we can access it using MyBase.

Shadowing – It hides a base class member in the derived class by using the new keyword. It is used to explicitly hide a member inherited from base class. new and override both cannot be used for the same member.

Example

class Employee
{
double m_dblBasicSalary;

public Employee(double dblBasicSalary)
{
m_dblBasicSalary = dblBasicSalary;
}

public virtual double CalculateSalary()
{
return m_dblBasicSalary;
}
}

class SalesPerson : Employee
{
double m_dblBasicSalary, m_dblSales, m_dblComm;

public SalesPerson(double dblBasicSalary, double dblSales, double dblComm):base(dblBasicSalary)
{
m_dblBasicSalary = dblBasicSalary;
m_dblSales = dblSales;
m_dblComm = dblComm;
}

public new double CalculateSalary()
{
return m_dblBasicSalary + (m_dblSales * m_dblComm);
}
}

class Program
{
static void Main(string[] args)
{
Employee oSalesPerson = new SalesPerson(1500, 20, 5);
double dblSalary = oSalesPerson.CalculateSalary();
Console.WriteLine(dblSalary);
Console.ReadKey();
}
}

Overriding: In overriding, methods have same names, same signatures, same return types but in different classes. C# uses virtual and override keyword for method overriding.Example

class Employee
{
double m_dblBasicSalary;

public Employee(double dblBasicSalary)
{
m_dblBasicSalary = dblBasicSalary;
}

public virtual double CalculateSalary()
{
return m_dblBasicSalary;
}
}

class SalesPerson : Employee
{
double m_dblBasicSalary, m_dblSales, m_dblComm;

public SalesPerson(double dblBasicSalary, double dblSales, double dblComm):base(dblBasicSalary)
{
m_dblBasicSalary = dblBasicSalary;
m_dblSales = dblSales;
m_dblComm = dblComm;
}

public override double CalculateSalary()
{
return m_dblBasicSalary + (m_dblSales * m_dblComm);
}
}

class Program
{
static void Main(string[] args)
{
Employee oSalesPerson = new SalesPerson(1500, 20, 5);
double dblSalary = oSalesPerson.CalculateSalary();
Console.WriteLine(dblSalary);
Console.ReadKey();
}
}

When you call the derived class object with a base class variable, in the case of overriding although you assign a derived class object to base class variable it will call the derived class function.
In case of shadowing or hiding the base class function will be called.