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++
What's the equivalent of this in C#. The nearest I've come to is this:Code:CMyClass* pMyObject = NULL; if ((pMyObject = GetMyObject()) != NULL) { // Got an existing object } else { pMyObject = new CMyClass("SomeArgument"); } pMyObject->MyMethod();
C#
I don't like this because:Code:CMyClass MyObject; // Default MyObject if (MyObjectAlreadyExists()) { // Overwrite default MyObject. MyObject = GetMyObject(); } else { // Overwrite default MyObject. MyObject = new CMyClass("SomeArgument"); } MyObject.MyMethod();
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?




Reply With Quote