As the question title suggests, I want to add an Action<string> to an interface. Is this possible? At the moment it says Interfaces cannot contain fields
As the question title suggests, I want to add an Action<string> to an interface.
Share
You’d need to add it as a property:
Without the get/set it’s just a field, and as the compiler points out interfaces can’t contain fields. This does mean that when you implement this interface you’ll need to supply the actual property as well (though obviously it can be a simple auto-property):
Given that, you can then use your
Action<string>from the interface:As Hans indicated, you can indicate in your interface just a
get(or even just aset) if you want. This doesn’t mean the class can’t have the other, it just means it won’t be accessible through the interface. For example:So in the above code, you could access the
YourActionproperty only as agetthrough the interface, but you couldsetorgetit from theFooclass.