Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 'set' to properties of interface in C#

Tags:

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?

like image 675
strager Avatar asked Mar 08 '09 16:03

strager


People also ask

Can we add properties in interface?

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.

How do you initialize an interface property?

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.

Is it possible to define properties in interface classes?

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.

Can I inherit property from class to interface?

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.


1 Answers

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.

like image 196
Chris Shaffer Avatar answered Dec 08 '22 09:12

Chris Shaffer