Multiple Inheritance in C# and VB.NET

C# and VB.NET supports single inheritance, however they do support multiple 'interface' inheritance:

Here's a sample demonstrating the same:

C#


//Single Inheritance

 

public class A

{

    public A() { }

}

 

public class B : A

 

{

    public B() { }

}

 

 

 

//Multiple Interface Inheritance

 

interface IComparable

{

    int CompareTo(object obj);

}

 

interface ISomethingElse

{

    int EqualTo();

}

 

 

 

public class Z :  IComparable, ISomethingElse

{

    public int CompareTo(object obj)

    {

        // implementation code goes here 

    }

 

public int EqualTo()

    {

        // implementation code goes here 

    }

 

}



VB.NET


'Single Inheritance

 

Public Class A

    Public Sub New()

    End Sub

End Class

 

Public Class B

    Inherits A

 

    Public Sub New()

    End Sub

End Class

 

 

 

'Multiple Interface Inheritance

 

Friend Interface IComparable

    Function CompareTo(ByVal obj As Object) As Integer

End Interface

 

Friend Interface ISomethingElse

    Function EqualTo() As Integer

End Interface

 

 

 

Public Class Z

    Implements IComparable, ISomethingElse

    Public Function CompareTo(ByVal obj As Object) _
     As Integer Implements IComparable.CompareTo

        ' implementation code goes here 

    End Function

 

    Public Function EqualTo() As Integer Implements _
       ISomethingElse.EqualTo

        ' implementation code goes here 

    End Function

 

End Class

1 comment:

  1. Hi,
    I need to create form2 with same controls as forms1( will Add new controls in Form2). Most of the methods in form1 will be used in form2, I'm wondering whether I can acheive re-using the code from form1 using Multiple Inheritance. Please help me.

    ReplyDelete