Search code examples
c#interfaceautomatic-properties

Auto Property that returns an interface


This is something curious that I saw in my coding today.

Here is the sample code:

public class SomeClass
{
   public IUtils UtilitiesProperty { get; set; }
}

public interface IUtils
{
   void DoSomething();
}

public class Utils : IUtils
{
   void DoSomething();
}

This compiles fine.

So what is UtilitiesProperty? Is it a Util? What if more than one class implemented IUTil? Would it fail the compile then?


Solution

  • It doesn't have any value until you give it one (or rather, it has the value null). If you assign it a Utils reference, then yes: it is a Utils, exposed via the IUtils interface. You can only give it null or things that implement IUtils.