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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

My Dreams said...

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.

Suprotim Agarwal said...

You are referring to Form Inheritance. Take a look here http://msdn.microsoft.com/en-us/library/s82eeh07(v=VS.90).aspx