Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • C# does not support multiple inheritance

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 321
    Comment on it

    C# does not support multiple inheritance because of diamond problem. To  understand it better, just take an example.

    Let's consider there is a class 'X' and it has two subclasses or derived classes 'Y' and 'Z'. As we know inheritance allows derived class to access the members and functions of the base class, so here 'Y' and 'Z' can inherit all the properties and members of the class 'X'. There is new class 'A' which inherit both 'Y' and 'Z' classes. This case of inheritance is called Multiple inheritance.

    According to inheritance concept of oops, this new class 'A' can inherit the functions/methods of class 'X'. Suppose that there is a method named getarea() in class 'X' and this method is overridden by both the subclasses 'Y' and 'Z'. So if class 'A' inherits getarea() method, then which method will be invoked.

     

    'Y''s getarea() implementation or 'Z''s getarea() implementation?

     

    So there will be an ambiguity in this problem which is called Multiple inheritance Diamond Problem.

     

    For Example: Code illustration to understand the diamond problem.

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace DiamondApp
    {
        class X    
        {
            public virtual void getarea()
            {
                Console.WriteLine("Class X");
            }
        }
     
        class Y:X
        {
            public override void getarea()
            {
                Console.WriteLine("Class Y");
            }
        }
     
        class Z:X
        {
            public override void getarea()
            {
                Console.WriteLine("Class Z");
            }
        }
     
        //DON'T WORK
        class A: Y, Z
        {
           
        }
     
        class Program
        {
            static void Main(string[] args)
            {
                A obj = new A();
                obj.getarea();
            }
                
        }
    }
    

     

     

    If you will try to access getarea() method in Class 'A', then it will throw an error:

     

    Error - ambiguous call. Two  copies getarea( ) exist in obj


     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: