In C#/C++, I can achieve this using the ternary operator although the code would be hideous. Are you sure you want to use this?
if ((myobject != null ? (myobject.myproperty != null ? (myobject.myproperty.myotherproperty != null ? myobject.myproperty.myotherproperty.value : null) : null) : null) != null)
class MyOtherProperty
{
public string value;
}
class MyProperty
{
public MyOtherProperty myotherproperty;
}
class MyObject
{
public MyProperty myproperty;
}
My Unit test code:
[TestMethod()]
public void TestTernaryOperator()
{
MyObject myobject = new MyObject();
Debug.WriteLine (string.Format ("{0}, {1}", myobject != null, myobject.myproperty != null));
Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject)));
myobject.myproperty = new MyProperty();
Debug.WriteLine (string.Format ("{0}, {1}, {2}", myobject != null, myobject.myproperty != null, myobject.myproperty.myotherproperty != null));
Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject)));
myobject.myproperty.myotherproperty = new MyOtherProperty ();
Debug.WriteLine (string.Format ("{0}, {1}, {2}, {3}", myobject != null, myobject.myproperty != null, myobject.myproperty.myotherproperty != null, myobject.myproperty.myotherproperty.value != null));
Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject)));
myobject.myproperty.myotherproperty.value = "Hello world";
Debug.WriteLine(string.Format("{0}, {1}, {2}, {3}", myobject != null, myobject.myproperty != null, myobject.myproperty.myotherproperty != null, myobject.myproperty.myotherproperty.value != null));
Debug.WriteLine(string.Format("IsNotNull = {0}", IsNotNull(myobject)));
}
bool IsNotNull(MyObject myobject)
{
bool isNotNull = (myobject != null ? (myobject.myproperty != null ? (myobject.myproperty.myotherproperty != null ? myobject.myproperty.myotherproperty.value : null) : null) : null) != null;
return isNotNull;
}