Label for "null if the object is null, or object.member if the object is not null"

I am trying to write a general extension method that allows me to do this:

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

NullOrPropertyOf() will return null if it is used for a null object (for example, if startDateXAttribute was null ), or returns a Func result if it is not null.

What does this extension method look like?

+6
generics c #
Sep 29 '10 at 0:17
source share
3 answers

There is no short form; the implementation of one of them is a rather frequently requested function. The syntax could be something like this:

 x = foo.?bar.?baz; 

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

We looked at it for C # 4, but it didn’t do it anywhere at the top of the priority list. We will keep in mind the hypothetical future versions of the language.

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

+24
Sep 29 '10 at 1:58
source share

The XAttribute Class provides an explicit conversion operator for this:

 XAttribute startDateXAttribute = // ... DateTime? result = (DateTime?)startDateXAttribute; 

In general, the best option is probably the following:

 DateTime? result = (obj != null) ? (DateTime?)obj.DateTimeValue : null; 
+1
Sep 29 '10 at 0:22
source share

Is this what you are looking for? I think this breaks if you pass a value type that is not null, but it should work when you use types with a null value. Please let me know if there is something that I missed.

 public static class Extension { public static T NullOrPropertyOf<T>(this XAttribute attribute, Func<string, T> converter) { if (attribute == null) { return default(T); } return converter.Invoke(attribute.Value); } } class Program { static void Main(string[] args) { Func<string, DateTime?> convertDT = (string str) => { DateTime datetime; if (DateTime.TryParse(str, out datetime)) { return datetime; } return null; }; Func<string, string> convertStr = (string str) => { return str; }; XAttribute x = null; Console.WriteLine(x.NullOrPropertyOf<string>(convertStr)); Console.WriteLine(x.NullOrPropertyOf<DateTime?>(convertDT)); XName t = "testing"; x = new XAttribute(t, "test"); Console.WriteLine(x.NullOrPropertyOf<string>(convertStr)); x = new XAttribute(t, DateTime.Now); Console.WriteLine(x.NullOrPropertyOf<DateTime?>(convertDT)); } } 
0
Sep 29 '10 at 15:45
source share



All Articles