views:

73

answers:

1

How to write an extension method that should check value of the object,if object is null then it should return null otherwise value{without doing casting at receiving end}.

something like...

public static object GetDefault(this object obj)
{
    if (obj == null) return null;
    else return obj;
}

I mean without casting can i check for null?

int? a=a.GetDefault();

ContactType type=type.GetDefault();   [For EnumType]

string  s=a.GetDefault()
+1  A: 

This should work:

public static class ExtensionMethods
{
    public static T GetObject<T>(this T obj, T def)
    {
        if (default(T).Equals(obj))
            return def;
        else
            return obj;
    }
}

I've added a parameter def because I expected you to want to return this default value when obj is null. Otherwise, you can always leave out the T def parameter and return null instead.

Pieter
No need for the `def` parameter. That's what the [`default`](http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx) keyword is for.
Oded
In a world where this method is useful, how about just `return obj ?? def;`
Anthony Pegram
@Oded, I assume this allows you to say `foo.GetDefault(new Foo { Bar = 7 })`, which will give you some default instance of `Foo` if `foo` is null.
Anthony Pegram
@Anthony Pegram - Better yet: `return obj ?? default(T);`
Oded
@Oded: I added the def parameter because your comment to the question :).
Pieter
@Oded, which for a nullable type is effectively the same as `return obj ?? obj;` or simply `return obj;`, because `default(T)` will be null.
Anthony Pegram
@Anthony Pegram - I guess it was not clear to me that the passed in object _is_ nullable.
Oded
@Oded - Well it must be, or the null coalescing operator would be useless, as would the check for null. But it looks like he stealthily edited the answer a bit, so I'm commenting on code that is now changed.
Anthony Pegram