The _ extension method will return null if the object is null, or it will return the property/method value.
public static class NullDotExtension
{
public static T _<O, T>(this O o, Func<O, T> t) where T : class
{
return (o == null ? (T)null : t(o));
}
}
public class NullDotObject
{
public string StringProperty { get; set; }
public NullDotObject ChildProperty { get; set; }
}
[TestClass]
public class NullDotTest
{
[TestMethod]
public void NullDotReturnsNull()
{
NullDotObject nullObject = null;
Assert.IsNull(nullObject._(n => n.StringProperty));
}
[TestMethod]
public void NullDotReturnsStringProperty()
{
NullDotObject nonNullObject = new NullDotObject { StringProperty = "String Value" };
Assert.AreEqual<string>("String Value", nonNullObject._(n => n.StringProperty));
}
[TestMethod]
public void NullDotReturnsChildProperty()
{
NullDotObject foo = new NullDotObject { StringProperty = "Foo" };
NullDotObject bar = new NullDotObject { ChildProperty = foo };
Assert.AreSame(foo, bar._(b => b.ChildProperty));
Assert.AreEqual(foo.StringProperty, bar._(b => b.ChildProperty)._(c => c.StringProperty));
}
[TestMethod]
public void NullDotReturnsNullString()
{
string foo = null;
Assert.IsNull(foo._(f => f.ToLower()));
}
[TestMethod]
public void NullDotReturnsString()
{
string foo = "FOO";
Assert.AreEqual("foo", foo._(f => f.ToLower()));
}
}
Fork
1 Feedback
I liked the idea of returning null or the correct value instead of getting an null exception :) - @fredrikn Saturday 25, 2010 9:53 AMYou must log in before you can give any feedback
0
I am now trying to work up an approach more like this:
[TestMethod]
public void ImmediateNull()
{
TestObject test = null;
string value = Safe<string>.Navigation(() => test.StringProperty);
Assert.IsNull(value);
}
[TestMethod]
public void NullProperty()
{
TestObject test = new TestObject { StringProperty = null };
string value = Safe<string>.Navigation(() => test.StringProperty);
Assert.IsNull(value);
}
[TestMethod]
public void NonNullProperty()
{
TestObject test = new TestObject { StringProperty = "foo" };
string value = Safe<string>.Navigation(() => test.StringProperty);
Assert.AreEqual("foo", value);
}
You must log in before you can post a comment


790
0


Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'