-1

-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?

crazyTech
  • 1,379
  • 3
  • 32
  • 67
  • 2
    *"How can C# allow"* is a broad question. What surprises you exactly? Properties are syntactical sugar for `get_X`, `set_X` methods. – Yuval Itzchakov Sep 29 '15 at 09:38
  • I'm just trying to understand. I always thought that ObjectId _id { get; set; } is a short-cut to declaring a member variable with it's standard getter and setter – crazyTech Sep 29 '15 at 09:43
  • That's called a [property](https://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx) in C#. It is valid as an interface member. – Yuval Itzchakov Sep 29 '15 at 09:45

1 Answers1

1

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.

Callum Bradbury
  • 936
  • 7
  • 14