Search code examples
c#oopclassinterfaceclass-design

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?


Solution

  • 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() { }
        }