1

Possible Duplicate:
C# if-null-then-null expression

What I miss in C# is the treatment of null references like in sql server:

var a = SomeObject.Property1.Property2.Property3.Property4

If any of properties is null then I get NullReferenceException. Sometimes it would be more convenient if a would be set to null with no error and I could simply check for this.

Similarly,

var a = SomeList.FirstOrDefault(...).Select(...)

this would also throw exception if sequence would contain no elements rather then setting a to null.

So my question: is there short and nice way (using extensions maybe?) to implement sql-like behaviour in these scenarios?

Community
  • 1
  • 1
ren
  • 3,843
  • 9
  • 50
  • 95

1 Answers1

0

This would only work with static properties, since an uninstantiated object is null. There would be no way doing this with extension methods either, as they take as their first parameter an instance of the object they are extending.

An ugly way of doing this ...

var a;
try {
   a = SomeObject.Property1.Property2.Property3.Property4;
} catch (NullReferenceException) { }
THBBFT
  • 1,161
  • 1
  • 13
  • 29
  • it seems that first parameter to extension method can be null and no error – ren Dec 10 '12 at 17:00
  • @ren The first declared parameter to an extension method is an instance of the class being extended. The extension does not need to declare any further parameters. Look here for general information on extensions:http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx – THBBFT Dec 10 '12 at 17:05
  • What I meant is [this](http://rextester.com/KSUSIK80614) – ren Dec 10 '12 at 17:13
  • @ren I played with that code ... I've never seen that site before, pretty handy. The extensions don't really help you unless you want to write an extension to replace every property of every object in your hierarchy. – THBBFT Dec 10 '12 at 17:34