Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Understanding polymorphism with abstract, virtual and override keyword in C#

The Abstract Modifier

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.

The Virtual Keyword

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.

The Override Modifier

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

Override Rules

  • The overridden base method is a virtual, abstract, or override method. In other words, the overridden base method cannot be static or non-virtual.
  • The overridden base method is not a sealed method.
  • The override method and the overridden base method have the same return type and same signature.
  • The override declaration and the overridden base method have the same declared accessibility (i.e public, internal etc).
  • The override declaration does not specify type-parameter-constraints-clauses. Instead the constraints are inherited from the overridden base method.

Reference: https://docs.microsoft.com/

Code example

In following example override modifier is used to implement the abstract and extend virtual implementation of an inherited methods Print () and Display (), always it will call extended/ modified members.

   public abstract class OverrideParent
    {
        //Concreate implementation, child allowed to override
        public virtual void Print()
        {
            Console.WriteLine("Parent virtual print");
        }
 
        //pure abstract member, child must override
        public abstract void Display();
    }

 

    public class ChildOverride :OverrideParent
    {
        public override void Print()
        {
            Console.WriteLine("1st level print override");
        }
        public override void Display()
        {
            Console.WriteLine("1st level implementation");
        }
    }

 

    public class NestedChildOverride: ChildOverride
    {
        public override void Print()
        {
            Console.WriteLine("2nd level print override");
        }
        public override void Display()
        {
            Console.WriteLine("2nd level override/implementation");
        }
    }

 

Client implementation 

   //How it works?
    class Program
    {
        static void Main(string[] args)
        {
            OverrideParent ParentTypeChildImpn = new ChildOverride();
            ChildOverride ChildTypeChildImpn = new ChildOverride();
            ChildOverride ChildTypeNestedChldImpl = new NestedChildOverride();
            NestedChildOverride NestedChildTypeNestedImpl= new NestedChildOverride();
 
            //parent abstract type and child implementation
            ParentTypeChildImpn.Print();
            ParentTypeChildImpn.Display();
 
            //child type and child implementations
            ChildTypeChildImpn.Print();
            ChildTypeChildImpn.Display();
 
            //Child type and derived nested implementations
            ChildTypeNestedChldImpl.Print();
            ChildTypeNestedChldImpl.Display();
 
            //Nested child type and nested implementations
            NestedChildTypeNestedImpl.Print();
            NestedChildTypeNestedImpl.Display();
 
 
          }
    }


Output:

 

Anonymous Types in C#

What is Anonymous Type in C#?

Anonymous types are easy way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

In simple language anonymous type is a class without name containing only read-only public properties.

Note:

  • The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
  • If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them.

How to create and use anonymous types in C#?

The following first example shows an anonymous type that is initialized with two properties named Id and Name.
Following 2nd example Anonymous type “ITDepartment” created with LINQ query select clause, first parameter is not named but used inferred anonymous type member(compiler gives name of department id) name and another parameter is named “depName”.

Example:

    public void ExmployeeData()
        {
            var Departments = GetAllDepartments();
 
            //1.  anonymous type “Employee” with properties named Id and Name.
            var Employee = new { Id="sk14",Name = "Shourya" };
 
            //2. anonymous type "ITDepartment" with LINQ query filter
            var ITDepartment = from dep in Departments
                               where dep.Name == "IT"
                               select new {dep.Id, DepName = dep.Name };
            //how to use it?
            Console.WriteLine("Employee Id :" + Employee.Id);
            Console.WriteLine("Employee Id :" + Employee.Name);
            Console.WriteLine("Employee Department Name :" + ITDepartment.FirstOrDefault().DepName); 
        }


Sample class and method to create in memory department collection.

   public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


public List<Department> GetAllDepartments()
        {
            var departments = new List<Department>();
 
            var ITDepartment = new Department
            {
                Id = 1,
                Name = "IT"
            };
 
            var AccountDepartment = new Department
            {
                Id = 2,
                Name = "Account"
            };
            departments.Add(ITDepartment);
            departments.Add(AccountDepartment);
 
            return departments;

        } 



How to return anonymous type with Web API?

In follwing code example web method returns anonymous type "Employee"

[HttpGet]
[Route("GetEmployeeData")]
 public IHttpActionResult GetEmployeeData()
   {
       //anonymous type Employee with properties named Id and Name.
       var Employee = new { Id = "sk14", Name = "Shourya" };
       // Status Code 200;
        return this.Ok(Employee);
   }

 

How to return anonymous type with method?

      //Return anonymous Type as object
        public object GetAnonymousData()
        {
            return new { Id = "sk14", Name = "Shourya" };
        }


       //Display anonymous Type values from object
        public void DisplayAnonymousData()
        {
            object refobj = GetAnonymousData();
            Type type = refobj.GetType();
            PropertyInfo[] fields = type.GetProperties();
            foreach (var field in fields)
            {
                string name = field.Name;
                var firstValue = field.GetValue(refobj, null);
                Console.WriteLine("Employee Name " + firstValue);
            }
        }

Explicit and implicit interface implementation in C#

Explicit interface implantation

With explicit interface implementations you can only access them when treating it as that interface.

i.e  ISedanCar.GetCarDetails(){};

Why explicit interface implantation?

If a class implements two interfaces (Multiple inheritance) and both interfaces with the same method signatures and different implementations, then you must implement explicitly.

Implicit interface implantation

Implicit is when you define your interface via a member on your class or normal class member implementation without interface name prefix.

Note:

  • There is no need to specify public/private/protected with explicit implementations since it will always be public as interfaces cannot have non-public members.
  • Interface's methods are not overridden, they are implemented, in case if you are trying child class as abstract class remember it. 

Explicit and implicit interface implementation examples

Interfaces

  interface ICar
    {
        void GetCarDetails();
    }
    interface ISedanCar
    {
        void GetCarDetails();
    }
    interface ISuvCar
    {
        void GetCarDetails();
    }

 

Implicit interface implantation example

//implicit implementation  
    public class BasicCar : ICar
    {
        //implicit         public void GetCarDetails()
        {
            Console.WriteLine("Details: Basic car features");
        }
    }  


//Hot it works?
    class Program
    {
        static void Main(string[] args)
        {
            var mycar = new BasicCar();
            mycar.GetCarDetails();
            ICar icar = new BasicCar();
            icar.GetCarDetails();
        }
    }


Output:

Details: Basic car features
Details: Basic car features

Implicit and Explicit implantation with single interface example

 //implicit and explicit implementation 
    public class Car : ISedanCar
    {
        //implicit implementation
        public void GetCarDetails()
        {
            Console.WriteLine("Details: common car features");
        }
 
        //explicit interface
        void ISedanCar.GetCarDetails()
        {
            Console.WriteLine("Details: sedan car features");
        }
    }

 

//How it works? 
    class Program
    {
        static void Main(string[] args)
        {
            Car mycar = new Car();
            mycar.GetCarDetails();
            ISedanCar mySedanCar=new Car();
            mySedanCar.GetCarDetails();
        }
    }

Output:

Details: common car features
Details: sedan car features

Explicit implantation with two interfaces (multiple inheritance) example

  //explicit implementation with multiple interface 
    public class LatestCar : ISedanCar, ISuvCar
    {
        //explicit interface implementation
        void ISedanCar.GetCarDetails()
        {
            Console.WriteLine("Details: sedan car features");
        }
 
        //explicit interface implementation
        void ISuvCar.GetCarDetails()
        {
            Console.WriteLine("Details: suv car features");
        }
    }


   //Hot it works with class instance?
    class Program
    {
        static void Main(string[] args)
        {
            var myCar = new LatestCar();
           //Showing compile time error with following
            myCar.GetCarDetails();
        }
    }


  //Hot it works with interface references?
    class Program
    {
        static void Main(string[] args)
        {
            ISedanCar mySedanCar = new LatestCar();
            mySedanCar.GetCarDetails();
            ISuvCar mySuvCar = new LatestCar();
            mySuvCar.GetCarDetails();
        }
    }


Output:

Details: sedan car features
Details: suv car features