Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add member variable to an interface in c#

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

like image 688
Nap Avatar asked Dec 23 '25 01:12

Nap


2 Answers

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();  
}
like image 159
Pawan Mishra Avatar answered Dec 24 '25 17:12

Pawan Mishra


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.

like image 44
Robert Fraser Avatar answered Dec 24 '25 17:12

Robert Fraser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!