javac#interfaceimplementationmembers

How can C# allow interface's to have member variables with getters/setters?


-For as long as I can remember, I always thought that interfaces in Java and C# would only allow the following in an interface --constants --method signatures

1) How can C# allow interface's to have member variables with getters/setters?

public interface IEntityBase
{
    ObjectId _id { get; set; }
}

2) Would Java allow for something similar to the aforementioned C# code?


Solution

  • A property is not a member variable. Think of it as a replacement for the old technique of a private variable with GetVarA() and SetVarA(int varA) methods exposing it.

    All a property really is, is that with neater syntax. That's why it can exist in an interface, as technically it's not defining a variable at all - your implementation of string MyName {get;} could have a private 'myName' member variable backing it up, whereas someone elses could grab the name from a database each time the property's Get was called.