Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign a delegate of one type to another even though signature matches

My morbid curiosity has me wondering why the following fails:

// declared somewhere
public delegate int BinaryOperation(int a, int b);

// ... in a method body
Func<int, int, int> addThem = (x, y) => x + y;

BinaryOperation b1 = addThem; // doesn't compile, and casting doesn't compile
BinaryOperation b2 = (x, y) => x + y; // compiles!
like image 479
Hobbes Avatar asked Dec 17 '10 03:12

Hobbes


1 Answers

C# has very limited support for "structural" typing. In particular, you can't cast from one delegate-type to another simply because their declarations are similar.

From the language specification:

Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types.

Try one of:

// C# 2, 3, 4 (C# 1 doesn't come into it because of generics)
BinaryOperation b1 = new BinaryOperation(addThem);

// C# 3, 4
BinaryOperation b1 = (x, y) => addThem(x, y);
var b1 = new BinaryOperation(addThem);
like image 185
Ani Avatar answered Sep 21 '22 13:09

Ani