Ronnie Overby
Ronnie Overby

Reputation: 46490

Help with c# 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 I'm not sure what to do with this expression object.

[enter image description here1

Upvotes: 1

Views: 241

Answers (3)

Ronnie Overby
Ronnie Overby

Reputation: 46490

Here's what I was after:

    public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> function, TResult defaultResult = default(TResult))
    {
        try
        {
            defaultResult = function(obj);
        }
        catch (NullReferenceException) { }
        return defaultResult;
    }

Upvotes: 0

Gabe Moothart
Gabe Moothart

Reputation: 32112

What you are trying to do sounds like Maybe.

Project Description:

Maybe or IfNotNull using lambdas for deep expressions in C#

int? CityId= employee.Maybe(e=>e.Person.Address.City);

Update: There is more discussion about how best to accomplish this sort of thing at this question.

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52818

Is this the sort of thing you're after?

public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> expression)
{
    if (obj == null)
        return default(TResult);

    try
    {
        return expression(obj);
    }
    catch(NullReferenceException)
    {
        return default(TResult);
    }
}

Upvotes: 1

Related Questions