SoftAllan SoftAllan - 7 months ago 62
C# Question

How does a C# Interface as a property work?

I am looking at the example from Using SignalR in WinForms and WPF in order to get an idea of how to implement SignalR in a .NET client application/dll. And I came across something that I don't get the concept of.

private IHubProxy HubProxy { get; set; }

When looking at the
I can see that it is an interface. I have always understood that you could not make an instance of an interface but it was rather a contract for a new class if you implement it telling the new class what methods it has to implement.

How does an interface setup as a property work?

Sid Sid

Of course you can't make an instance for an Interface but you can make an instance of a class that implements that interface.

Let me make an example, consider the following code:

interface IEmailSender
   void SendEmail();

public class EmailSender : IEmailSender 
   public void SendEmail()
      throw new NotImplementedException();

   public void DoOtherStuff()
      throw new NotImplementedException();

Now the following code is perfectly legal:

IEmailSender mailSender = new EmailSender(); 
mailSender.SendEmail(); //Works just fine
mailSender.DoOtherStuff(); //Will raise an error at compile time

Usage in a property

Let's build a test class:

public class Test 
    public IEmailSender MyEmailSender;

Now let's check the following code:

var testOBJ = new Test();
testOBJ.MyEmailSender = new IEmailSender(); //Raises a compile time error, as you outlined yourself
testOBJ.MyEmailSender = new EmailSender(); //Perfectly Legal

Basically you can asign to that property anything that implements that interface

Hope it's clear now :)