Interface with getter and setter in c#
No. I think you misunderstood. That article is about the possibility of having an interface with a readonly property (a property with only getter). But, if you need, you can put also the setter in the interface:
interface IHasProperty
{
string Property{ get;set; }
}
class HasProperty:IHasProperty
{
public string Property{ get;set; }
}
You can use property syntax. Use this combination:
interface ISomething
{
string Test { get; }
}
class Something : ISomething
{
public string Test { get; private set; }
}
You can of course add full implementations for the getters in Something.Test, if you choose to. I only used backing fields for brevity.
Remember that an interface defines the bare minimum set of things you must implement. You can add any gravy (new methods, accessors, members, etc) on top that you want. You could even add a public setter:
interface ISomething
{
string Test { get; }
}
class Something : ISomething
{
public string Test { get; set; } // Note that set is public
}
The only restriction is that someone can't use the gravy you add, unless they have a reference of the concrete type (the class, not the interface), or a different interface that defines the methods you added.
Yes, just omit set;
from the property declaration. For example:
interface IName
{
string Name { get; }
}