Mohan Kumar
Mohan Kumar

Reputation: 6056

Setting default value for properties of Interface?

I have an Interface which contains one property. I need to set the default value for that property. How to do that?. Also is it good practice to have a default value for a property in Interface? or here using an abstract class instead is a apt one?

Upvotes: 13

Views: 33226

Answers (4)

Ramil Aliyev 007
Ramil Aliyev 007

Reputation: 5442

This is possible with static fields.Because, interfaces cannot contains instance fields. Static fields are not instance fields.

Or you can use literal values. For example, I use Age property in interface below.

public interface IMyDefault
{
    private static string _name = "Yusif";

    // Has default implementation
    string Name
    {
        get
        {
            return _name;
        }

        set
        {
            _name = value;
        }
    }

    int Age { get => 18; }

    // Hasn't default implementation
    string Surname { get; set; }
}

public class MyDefault : IMyDefault
{

    // We only implement Surname in MyDefault.cs
    public string Surname { get; set; }
}

But, you can access default implemented properties only after cast object to interface.

For example:

Code below will not compile

MyDefault myDefault1 = new MyDefault();

Console.WriteLine(myDefault1.Name);

Code below will compile

IMyDefault myDefault2 = new MyDefault();

Console.WriteLine(myDefault2.Name);

Upvotes: 0

Ibrahim ULUDAG
Ibrahim ULUDAG

Reputation: 480

With C#8, interfaces can have a default implementation. https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/

Upvotes: 13

Petar Ivanov
Petar Ivanov

Reputation: 93030

You can't set a default value to a property of an interface.

Use abstract class in addition to the interface (which only sets the default value and doesn't implement anything else):

    public interface IA {
        int Prop { get; }

        void F();
    }

    public abstract class ABase : IA {
        public virtual int Prop
        {
            get { return 0; }
        }

        public abstract void F();
    }

    public class A : ABase
    {
        public override void F() { }
    }

Upvotes: 14

Adam Ralph
Adam Ralph

Reputation: 29956

Interfaces contain no implementation. All they do is state member signatures.

An implementation of an interface is free to have whatever default value it likes for any property.

E.g. an abstract class can return a default value for any of it's properties.

Upvotes: 1

Related Questions