How to add member variable to an interface in c#

17,565

Solution 1

public interface IBase {
  void AddData();
  void DeleteData();
}

public abstract class AbstractBase : IBase {
  string ErrorMessage;
  public abstract void AddData();
  public abstract void DeleteData();
}

Workd for me. You were missing the "public" and "void" on the abstract class methods.

Solution 2

You cannot add fields to an interface.Interface can only contain methods , so only methods , properties , events can be declared inside an interface decleration.In place of field you can use a property.

public interface IBase {  
  string ErrorMessage {get;set;}
  void AddData();  
  void DeleteData();  
}

Solution 3

Since interfaces only declare non-implementation details, you cannot declare a member variable in an interface.

However, you can define a property on your interface, and implement the property in your class.

Share:
17,565
hila shmueli
Author by

hila shmueli

● System/Software Engineer, developing Web and desktop applications with broad experience in .NET and Java.

Updated on June 05, 2022

Comments

  • hila shmueli
    hila shmueli almost 2 years

    I know this may be basic but I cannot seem to add a member variable to an interface. I tried inheriting the interface to an abstract class and add member variable to the abstract class but it still does not work. Here is my code:

    public interface IBase {
      void AddData();
      void DeleteData();
    }
    
    public abstract class AbstractBase : IBase {
      string ErrorMessage;
      public abstract void AddData();
      public abstract void DeleteData();
    }
    
    public class AClass : AbstractBase {
      public override void AddData();
      public override void DeleteData();
    }
    

    updated base on comment of Robert Fraser

  • xoxo
    xoxo over 5 years
    Hi Robert Fraser, I am having doubt here. Can you please explain why do we have to inherit an interface to an abstract class instead of normal class. Because in abstract class we cannot give implementation of interface members. Could you please explain the technical reason? I am not too good at c#