Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add an Action<string> to an interface?

Tags:

c#

.net

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

like image 623
Jon Avatar asked Mar 19 '12 14:03

Jon


1 Answers

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.

like image 162
James Michael Hare Avatar answered Oct 02 '22 18:10

James Michael Hare