|
-
March 11th, 2004, 04:56 AM
#1
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?
-
March 11th, 2004, 05:15 AM
#2
Re: C# equivalent of C++ NULL pointers for objects?
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();
If you think you CAN, you can, If you think you CAN'T, you are probably right.
Have some nice Idea to share? Write an Article Online or Email to us and You may WIN a Technical Book from CG.
-
March 11th, 2004, 05:21 AM
#3
Does not create an object. MyObject is effectively a pointer and at this point contains null. (I think).
Code:
CMyClass pMyObject = null;
if ((pMyObject = GetMyObject()) != null)
{
// Got an existing object
}
else
{
pMyObject = new CMyClass("SomeArgument");
}
pMyObject.MyMethod();
-
March 11th, 2004, 05:22 AM
#4
Thanks guys; I remember now reading that you have to use new to create an object. The implications didn't sink in, but they have now!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|