Ronnie Overby
Ronnie Overby

Reputation: 46490

Need help creating extension method in C# with generics and lambda expression

I'm pulling all of the advanced features together for this one, but haven't worked with generics or lambda expressions very much:

Here's example usage of the method I want to create:

MyClass mc = null;
int x = mc.TryGetOrDefault(z => z.This.That.TheOther); // z is a reference to mc
// the code has not failed at this point and the value of x is 0 (int's default)
// had mc and all of the properties expressed in the lambda expression been initialized
// x would be equal to mc.This.That.TheOther's value

Here's as far as I've gotten, but Visual Studio is complaining:

enter image description here

Upvotes: 0

Views: 163

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503439

You haven't made your method generic in TResult. You want something like:

public static TResult TryGetOrDefault<TSource, TResult>
    (this TSource obj, Expression<Func<TSource, TResult>> expression)

Upvotes: 5

Related Questions