5

I have a method on an interface:

Someclass DoSomething(Someclass whatever);

I can't do .Returns(x => x) because of the error:

cannot convert lambda expression to type Someclass because it is not a delegate type.

Any ideas?

Bleh
  • 441
  • 3
  • 14
  • Possible duplicate of [Cannot convert lambda expression to type 'string' because it is not a delegate type](http://stackoverflow.com/questions/19197481/cannot-convert-lambda-expression-to-type-string-because-it-is-not-a-delegate-t) – Rosdi Kasim Apr 19 '17 at 21:27
  • use proper tag and don't include it question title – Rahul Apr 19 '17 at 21:27

2 Answers2

9

Take a look at these method overloads:

Returns(TResult value)
Returns<T>(Func<T, TResult> valueFunction)

It seems quite obvious for you that C# compiler should pick second overload. But actually C# compiler is unable to infer type of generic parameter T from argument x => x which you are passing. That's why compiler picks non-generic version of method and tries to convert lambda to SomeClass.

To fix this issue you should help compiler to infer type of generic parameter T. You can do it by explicitly specifying type of delegate argument:

.Returns((SomeClass x) => x);

Or you can specify type of T manually

.Returns<SomeClass>(x => x)
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 1
    FYI this appears to not work for `mock.SetupSequence(...).Returns(...)` calls , only `mock.Setup(...).Returns(...)` calls – ElFik Feb 25 '20 at 19:05
1

You can create a instance of someclass and return the same like

someclass cl = new someclass
{
//property initialization
};

mockinstance.Setup(s => s.DoSomething(cl)).Returns(cl);
Rahul
  • 76,197
  • 13
  • 71
  • 125