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
You'd need to add it as a property:
public interface IYourInterface
{
Action<string> YourAction { get; set; }
}
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):
public class Foo : IYourInterface
{
public Action<string> YourAction { get; set; }
// ...
}
Given that, you can then use your Action<string>
from the interface:
IYourInterface iFoo = new Foo();
iFoo.YourAction = s => Console.WriteLine(s);
iFoo.YourAction("Hello World!");
As Hans indicated, you can indicate in your interface just a get
(or even just a set
) 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:
public interface IYourInterface
{
Action<string> YourAction { get; }
}
public class Foo : IYourInterface
{
public Action<string> YourAction { get; set; }
}
So in the above code, you could access the YourAction
property only as a get
through the interface, but you could set
or get
it from the Foo
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With