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?
Asked
Active
Viewed 2.6k times
3 Answers
12
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() { }
}

Petar Ivanov
- 91,536
- 11
- 82
- 95
-
1Petar, Does, Use abstract class in addition to the interface means,i should change the Interface to an abstract class? – Mohan Kumar Oct 12 '11 at 05:35
-
1No it means use an abstract class which implements the interface and then extend it. – Petar Ivanov Oct 12 '11 at 09:31
10
With C#8, interfaces can have a default implementation. https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/

Ibrahim ULUDAG
- 450
- 3
- 9
-
this does not seem to include default property values, though it does include default property implementations – Dave Cousineau Sep 03 '23 at 01:14
1
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.

Adam Ralph
- 29,453
- 4
- 60
- 67
-
The sentence "Interfaces contain no implementation." is now invalid: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#concrete-methods-in-interfaces – derekbaker783 Dec 15 '21 at 17:30
-
Sure, but I'm not going to go back and update old answers. They have timestamps, as do subsequent versions of languages, etc. – Adam Ralph Dec 16 '21 at 22:55