C# equivalent of C++ NULL pointers for objects?
I'm trying to improve my understanding of C#.
In C++ I could use NULL objects to check for the existance of an object, which gives the following consise pattern:
C++
Code:
CMyClass* pMyObject = NULL;
if ((pMyObject = GetMyObject()) != NULL)
{
// Got an existing object
}
else
{
pMyObject = new CMyClass("SomeArgument");
}
pMyObject->MyMethod();
What's the equivalent of this in C#. The nearest I've come to is this:
C#
Code:
CMyClass MyObject; // Default MyObject
if (MyObjectAlreadyExists())
{
// Overwrite default MyObject.
MyObject = GetMyObject();
}
else
{
// Overwrite default MyObject.
MyObject = new CMyClass("SomeArgument");
}
MyObject.MyMethod();
I don't like this because:
I have to create a default MyObject, and then throw it away when I overwrite it, which seems inefficient. I don't want to use the object type instead as I lose type checking, and have to then cast to CMyObject.
I have to separate checking whether MyObject already exists from getting it.
Am I missing something?
Re: C# equivalent of C++ NULL pointers for objects?
Quote:
Originally posted by astanley
C#
Code:
//somewhere in your class
CMyClass MyObject = null;
//somewhere in some function
if (MyObject!=null)
{
// Overwrite default MyObject.
MyObject = GetMyObject();
}
else
{
// Overwrite default MyObject.
MyObject = new CMyClass("SomeArgument");
}
MyObject.MyMethod();