user2994682
user2994682

Reputation: 503

C#, Assign an Action to a Delegate

I understand that an Action is a Delegate, but I'm receiving the following compile time error trying to assign an Action to a Delegate.

Cannot implicitly convert type 'System.Action' to 'ADelegate'

public delegate void ADelegate();
Action act = () => Console.WriteLine ("test");
ADelegate del = act;

How can I assign act to del?

Upvotes: 6

Views: 4329

Answers (2)

Martin Costello
Martin Costello

Reputation: 10862

Can you not just do this?

public delegate void ADelegate();
ADelegate del = () => Console.WriteLine("test");

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149020

C# doesn't support casting or converting between delegate types.

Try creating a new ADelegate like this:

Action act = () => Console.WriteLine ("test");
ADelegate del = new ADelegate(act);

Or alternatively:

Action act = () => Console.WriteLine ("test");
ADelegate del = act.Invoke;

Upvotes: 10

Related Questions