C# extension method for setting to new instance if null -
i have following extension methods me check , instantiate objects if null. top 2 work fine not useful.
public static bool isnull<t>(this t t) { return referenceequals(t, null); } public static t newifnull<t>(this t t, func<t> createnew) { if (t.isnull<t>()) { return createnew(); } return t; } public static void ensure<t>(this t t, func<t> createnew) { t = t.newifnull<t>(createnew); }
ultimately like
ilist<string> foo; ... foo.ensure<ilist<string>>(() => new list<string>());
the ensure method not achieve desired effect, setting foo
instance of list<string>
if null , set otherwise.
if know can tweak ensure method achieve appreciate help.
thanks, tom
you need distinguish between objects , variables. object can never null - value of variable can be. you're not trying change object (which would work) - you're trying change value of caller's variable.
however, arguments passed value default, means extension method changes parameter (the variable declared within method), has no effect on caller's variable. you'd able change parameter ref
achieve pass-by-reference semantics, extension methods can't have ref
or out
first parameter.
as others have said, using null-coalescing operator (??) better bet. note in expression:
foo = foo ?? new list<string>();
the new list not constructed unless foo
null. right hand operand of ??
not evaluated unless needs be.
Comments
Post a Comment