Default implementation of a method for C# interfaces?

后端 未结 6 2020
梦如初夏
梦如初夏 2020-12-24 05:35

Is it possible to define an interface in C# which has a default implementation? (so that we can define a class implementing that interface without implementing that particul

6条回答
  •  感动是毒
    2020-12-24 06:01

    Short Answer:

    No, you cannot write implementation of method in interfaces.

    Description:

    Interfaces are just like contract ,so that the types that will inherit from it will have to define implementation, if you have a scenario you need a method with default implementation, then you can make your class abstract and define default implementation for method which you want.

    For Example:

    public abstract class MyType
    {
        public string MyMethod()
        {
          // some implementation
        }
    
        public abstract string SomeMethodWhichDerivedTypeWillImplement();
    }
    

    and now in Dervied class:

    public class DerivedType : MyType
    {
      // now use the default implemented method here
    }
    

    UPDATE (C# 8 will have support for this):

    C# 8 will allow to have default implementation in interfaces

提交回复
热议问题