Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 51,480 times

Contents

Related Categories

The Quick & Dirty .NET Guide to C#/VB OOP - Interfaces

DMarko1

Interfaces

Back in our section on abstract classes we dealt with interfaces in comparison. We briefly explained that they look like classes but they don't get instantiated in your page as would a typical class. Reason for this is that they are used or inherited by other classes for a particular functionality as a contract . In other words, they provide specs or behaviors for other classes as to their use or redefinition rather than their direct implementation. Incidentally, interfaces are C#'s answer to C++'s multiple inheritance .

Now to create an interface we'd declare an interface with the interface keyword and specify the interface name. Good naming convention suggests a capital "I" before the interface name to avoid any confusion and to confirm a naming structure.

Key points:

  • As a rule, interfaces are always, by default public, as are their members.
  • Interfaces could contain the following members: methods, properties and events
  • All the members within an interfaces, whether a method or field, cannot themselves contain anything, they would need to be empty without any body text.
  • Interfaces themselves could even inherit other interfaces, and without having to implementing all its methods, unlike classes, which have to!
  • Both classes as well as structs could inherit multiple interfaces.

In addition, whatever methods or properties the interfaces contain, they would all have to be implemented upon inheriting them in your new class. Still if you prefer you can conditionally check if an actual interface is valid from within by using the is operator.

Furthermore, implementing and redefining methods and properties of an interface can be done two ways: implicitly , that we do, via our publicly and or virtually declared members, or explicitly, which are referenced directly via the interface name.

Below, the C# examples are no different than before, however, the VB implementation requires some attention. Multiple Inheritance as we've touched upon in light of interfaces, can be accomplished this way:

[C#]
interface IAllStats
{
    int ShowSquareFeet { get; } //Interface property
    void ShowOwner(); //Interface method

}
interface IAllStats2
{
    string OwnerName { get; set; } //Interface property
    void ShowLocation(); //Interface method

}

public class UseBothInterfaces : IAllStats, IAllStats2 //Multiple Inheritance feature of Interfaces
{
    // Field for interface property
    private string _OwnerName;

    // Property implementation
    public int ShowSquareFeet
    {
        get { return 3600; } //Read only value
    }
    public string OwnerName
    { //Getter and Setter property
        get { return _OwnerName; }
        set { _OwnerName = value; }
    }
    public void ShowOwner() { OwnerName = "Pete"; } // ShowOwner() method implemented, assigning OwnerName
    public void ShowLocation() { } // ShowLocation() method implemented

    public object ShowStats()
    {
        //ShowOwner(); // Method called - overrides property
        return OwnerName + " owns a house that's " + ShowSquareFeet + " square feet";
    }

}

[VB]
Interface IAllStats
    ReadOnly Property ShowSquareFeet() As Integer 'This property is only read only
    Function ShowOwner() As String
End Interface
Interface IAllStats2
    Property OwnerName() As String
    Function ShowLocation() As String
End Interface

Public Class UseBothInterfaces : Implements IAllStats, IAllStats2 'Multiple Inheritance feature of Interfaces
    Private _OwnerName As String
    Public ReadOnly Property ShowSquareFeet() As Integer Implements IAllStats.ShowSquareFeet
        Get
            Return 3600 'Read only value
        End Get
    End Property
    Property OwnerName() As String Implements IAllStats2.OwnerName 'Getter and Setter property
        Get
            Return _OwnerName
        End Get
        Set(ByVal Value As String)
            _OwnerName = value
        End Set
    End Property

    Public Function ShowOwner() As String Implements IAllStats.ShowOwner
        OwnerName = "Pete"
    End Function
    Public Function ShowLocation() As String Implements IAllStats2.ShowLocation
        ' ShowLocation() method implemented
    End Function

    Public Function ShowStats() As Object
        ' ShowOwner() ' Method called - overrides property - See results below
        Return OwnerName & " owns a house that's " & ShowSquareFeet & " square feet"

    End Function

End Class

Implementing this is as easy as this:

[C#]
UseBothInterfaces StatsInter = new UseBothInterfaces();
StatsInter.OwnerName = "Jim";
Response.Write (StatsInter.ShowStats());

[VB]
Dim StatsInter As UseBothInterfaces = New UseBothInterfaces()
StatsInter.OwnerName = "Jim"
Response.Write (StatsInter.ShowStats())

OK, now what took place? Well, we created two interfaces that include both method and properties (both a standard string property and readonly integer property). Next we set up our class that inherits multiple interfaces, and we then begin defining their members from our two interface templates.

In our above .aspx page code, we instance our class UseBothInterfaces() , and proceed to assign our object's OwnerName() method a value, and then write out our results. Our ShowStats() method is set up to do two things. Call, thus implement, the ShowOwner() method along with its code (which overwrites Jim with Pete ), and or return to us the OwnerName that was set from our page's object instantiation, alongside our ShowSquareFeet() method's measurements that were internally already assigned.

Therefore, working with interfaces offers us the ability and has demonstrated how we could inherit and implement multiple interfaces in a class, assign and retrieve property values, implement methods and return results that can be accomplished either internally or externally through our web page from our two contracts. In our example we decided to implement both interfaces, and all define all their members.

And our results:

Another point to note is that our VB code in comparison to C# requires the Implements keyword referencing the implemented interface and method. Again upon implementing an interface, you must implement all the members of that interface, unlike abstract classes that do not support multiple inheritance, but are allowed to choose what members you wish to implement, as long as you specify to the contrary.

Quick observation: Creating an instance of the class inheriting multiple interfaces is demonstrate above in our BothInterfaces() method. Now notice that we create an instance and we could reference any class that implements any interface. Moreover, interfaces due to their insistent complete implemenation schema could go a long way in preventing runtime bugs.

As we'll explore polymorphism , you'll discover instantiation of a different kind, that applies to interfaces as well.

Dimitrios, or Jimmy as his friends call him, is a .NET developer/architect who specializes in Microsoft Technologies for creating high-performance and scalable data-driven enterprise Web and desktop applications. Till now Jimmy has authored nearly two dozen .NET articles, published on Dot Net Junkies, 4 Guys From Rolla, Sitepoint, MSDN Academic Alliance, Developers.NET, The Official Microsoft ASP.NET Site, and here on Developer Fusion, covering various unique and advanced techniques on .NET.

Comments

  • Re: [4341] The Quick & Dirty .NET Guide to C#/VB OOP

    Posted by Yoenuts on 25 Jul 2006

    hello,


    I am very impressed by your tutorial as it finally allowed me to grasp the syntax behind OOP programming with .net.
    Only what I did not understand is how and where do I complile the .cs ...

  • Re: [4341] The Quick & Dirty .NET Guide to C#/VB OOP

    Posted by ggorcsos on 22 Jun 2006

    Honestly I believe that the basic idea of the OOP was really great, but to be able to use it one really has to have the head as a water melon. There is too much theory, too many ther...

  • Posted by James Crowley on 20 May 2005

    Though from personal experience I'd say 99.99% of the time, you'd want private member variables and public properties... ;)

  • Posted by DMarko1 on 22 Apr 2005

    Hi Ehx,

    That's true, and it's funny that in all my other articles I always write all private variables with public properties. i.e. - [url="http://www.developerfusion.co.uk/show/4676/1/"]Building a...

  • Confusion about this article (Get ,Set)

    Posted by aalhussein on 22 Apr 2005

    After reading your article, http://www.developerfusion.com/show/4341/6/
    I got realy confused!!

    from what I know from the book below, I declare private property, then declare public (get , set )
    W...