Library tutorials & articles

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

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.

Comments

  1. 25 Jul 2006 at 13:14

    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 to a dll? I cannot do it on the server. Do I do it on my local computer and then upload?


    http://www.developerfusion.co.uk/show/4341/5/

  2. 22 Jun 2006 at 06:29

    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 therms and the class theory really feels like puting each part of the program into a separate box and then figuring out how to drill a way between them. I started to learn C++ OOP at least 20 time and after a couple of weeks I did not even had an idea what it is about (note: I am not a proffesional programmer)...

    I believe that: "The use of a programming language should be as simple as a pie and the algorithm should be the part where people spend the most of their time..."

    When I do C# programming I do all public and it works great for me. Simply keep it simple!!!

    Is there any web page or book where I could find how to do Non-OOP C# programming?

    Sincerely,

    Gabor Gorcsos

     

     

     

  3. 20 May 2005 at 23:21

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

  4. 22 Apr 2005 at 18:00

    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. - Building a Full-Featured Custom DataGrid Control. It's just one of those overlooked things. Oh well.

  5. 22 Apr 2005 at 17:26

    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 )
    What you presented in your article is you declared public property,then  made the (get,set) private)


    I have put this simple comparison code , so please advice your point, What is the logic behind reversing the modifier(public to private and vis versa).
    thanks
    Ehx
     
        // what is in the book (Begining Asp.Net Database using C# p 321)
           private string Country;
           public string Country
           {
               get{return _Country;}
               set{
    Country= value;}
           }


                  // what is in web article ( in your article)
           public string Name;
           private string _Name
           {
               get{return Name;}
               set{Name= value;}
           }

  6. 01 Jan 1999 at 00:00

    This thread is for discussions of The Quick & Dirty .NET Guide to C#/VB OOP.

Leave a comment

Sign in or Join us (it's free).

Dimitrios Markatos 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 deskto...
AddThis

Related podcasts

  • A Practical Look at Silverlight 2 Part 1

    Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

We'd love to hear what you think! Submit ideas or give us feedback