Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for "null if object is null, or object.member if object is not null" [duplicate]

Tags:

c#

generics

I'm trying to write a generic extension method that let's me do this:

this.startDate = startDateXAttribute.NullOrPropertyOf<DateTime>(() =>
{
    return DateTime.Parse(startDateXAttribute.Value);
});

NullOrPropertyOf() would return null if it's used on a null object (e.g. if startDateXAttribute was null), or return the result of a Func if it's not null.

What would this extension method look like?

like image 216
SnickersAreMyFave Avatar asked Sep 29 '10 00:09

SnickersAreMyFave


2 Answers

There's no short form for that; implementing one is a fairly frequently requested feature. The syntax could be something like:

x = foo.?bar.?baz;

That is, x is null if foo or foo.bar are null, and the result of foo.bar.baz if none of them are null.

We considered it for C# 4 but it did not make it anywhere near the top of the priority list. We'll keep it in mind for hypothetical future versions of the language.

UPDATE: C# 6 will have this feature. See http://roslyn.codeplex.com/discussions/540883 for a discussion of the design considerations.

like image 97
Eric Lippert Avatar answered Oct 14 '22 12:10

Eric Lippert


The XAttribute Class provides an explicit conversion operator for this:

XAttribute startDateXAttribute = // ...

DateTime? result = (DateTime?)startDateXAttribute;

For the general case, the best option is probably this:

DateTime? result = (obj != null) ? (DateTime?)obj.DateTimeValue : null;
like image 30
dtb Avatar answered Oct 14 '22 14:10

dtb