I am looking to 'extending' an interface by providing set accessors to properties in that interface. The interface looks something like this:
interface IUser
{
string UserName
{
get;
}
}
I want something like this:
interface IMutableUser : IUser
{
string UserName
{
get;
set;
}
}
I need the inheritence. I cannot copy the body of IUser
into IMutableUser
and add the set accessors.
Is this possible in C#? If so, how can it be accomplished?
An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain fields, auto-implemented properties. The following interface declares some basic functionalities for the file operations. You cannot apply access modifiers to interface members.
You just specify that there is a property with a getter and a setter, whatever they will do. In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.
Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.
A class implements an interface, it does not inherit it. However, if you want to provide code for a derived class, you can just write a base class to contain it.
I don't see any reason why what you have posted shouldn't work? Just did a quick test and it compiles alright, but gives a warning about hiding. This can be fixed by adding the new keyword, like this:
public interface IMutableUser : IUser
{
new string Username { get; set; }
}
An alternative would be to add explicit set methods; eg:
public interface IMutableUser : IUser
{
void SetUsername(string value);
}
Of course, I'd prefer to use setters, but if it's not possible, I guess you do what you have to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With