Nap
Nap

Reputation: 8286

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

Upvotes: 3

Views: 19761

Answers (5)

Robert Fraser
Robert Fraser

Reputation: 10927

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.

Upvotes: 2

Pawan Mishra
Pawan Mishra

Reputation: 7268

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();  
}

Upvotes: 13

Zach Johnson
Zach Johnson

Reputation: 24232

Did you mean a property instead of a field?

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

public abstract class AbstractBase : IBase {
  abstract string ErrorMessage { get; set; }

  // also, you need to declare a return type for the methods
  abstract void AddData();
  abstract void DeleteData();
}

Upvotes: 0

rh.
rh.

Reputation: 1721

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.

Upvotes: 1

tyranid
tyranid

Reputation: 13318

If it is something implementing classes need to implement then use a property definition i.e.

That said if it is something which needs to be private then that it not something which should be in an interface anyway.

Upvotes: 0

Related Questions