Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you think "auto interface implementation" would be useful in .NET / C# [closed]

Consider this:

public class interface Person : IPerson
{
  int ID { get; protected set; }
  string FirstName { get; set; }
  string LastName { get; set; }
  string FullName { get { return FirstName + " " + LastName; } }
}

And this:

public class StubPerson : IPerson
{
    int ID { get { return 0; protected set { } }
    string FirstName { get { return "Test" } set { } }
    string LastName { get { return "User" } set { } }
    string FullName { get { return FirstName + " " + LastName; } }
}

Usage:

IPerson iperson = new Person();

Or:

IPerson ipersonStub = new StubPerson();

Or:

IPerson ipersonMock = mocks.CreateMock<IPerson>();

So in effect we are declaring the IPerson interface and the Person class at the same time:

public class interface Person : IPerson

Do you think it would be useful to have this kind of support in .NET/C#?

Edit:

Due to mass confusion I think I need to clarify the proposed purpose:

Without this feature you would have to write:

interface IPerson
{
  int ID { get; }
  string FirstName { get; set; }
  string LastName { get; set; }
  string FullName { get; }
}

as well as this:

public class Person : IPerson
{
  int ID { get; protected set; }
  string FirstName { get; set; }
  string LastName { get; set; }
  string FullName { get { return FirstName + " " + LastName; } }
}

I'm not proposing any semantic change at all.

like image 877
Jonathan Parker Avatar asked Mar 18 '09 00:03

Jonathan Parker


1 Answers

Let me see if I am understand what you're asking:

Why can't we declare an interface:

interface IPerson
{
    string Name {get;set;}
    int ID {get;set;}
}

And classes which implement that interface will inherit its properties without having to re-declare them:

class Person : IPerson { } 
//person now has properties Name and ID

The reason you can't do this is even though the text of your interface code and your class code are very similar, they mean very different things. The interface simply says "implementor will have a string Name with getter and setter". It is the class which says "return private field when getter for name is invoked." Even if you use the auto-property shortcut to let the compiler implement that logic, it is still logic, which belongs in the class. Just because:

string Name {get;set;}

looks the same in an interface and in a class, it does not mean even remotely the same thing.

It would be very dangerous for the compiler to implement arbitrary logic to fulfill your contracts for you, instead of complaining at compile time that you haven't implemented them. It could introduce bugs very difficult to track down. Having compilers fall back to default behavior when no behavior is defined is a very, very bad idea.

like image 140
Rex M Avatar answered Oct 06 '22 20:10

Rex M