How to test if a variable is initiallized?

B

Bob

I have a reference type variable and I need to check whether it has actual
value or not. However, the following fails:


MyUserClass myObj;
........
if (myObj== null) {
......

I get the compiler error: Operator '==' cannot be applied to operands of
type 'MyUserClass' and '<null>'

How do I check if the variable is initialized before I call the public
members then?

Thanks
Bob
 
A

Andreas Håkansson

Bob,

When you declare your variable you should do the following
MyUserClass myObj = null. Then you will be able to do the
check you wanted.

MyUserClass myObj = null
if( myObj == null )
myObj = new MyUserClass();

However I am not sure if this is your problem based on the error
description. Have you perhaps overloaded the == operand in the
MyUserClass class?

HTH,

//Andreas
 
B

Bob

My bad! Upon further scrutiny, I found the type "MyUserClass" was defined
as a struct, not a class! That's the problem. Value types don't have null
value of course... Thanks. Bob
 
A

Andreas Håkansson

LC,

Not true. It all depends on the scope of the variable, if you declare it
on a class level scope:

publi class Foo
{
private MyUserClass myObj;

public Foo()
{
}

public MyUserClass Bar()
{
if( myObj == null )
myObj = new MyUserClass();
return myObj;
}
}

Then it will work. How ever if you declare is just before the class, i.e.
inside
the Bar() method

public MyUserClass Bar()
{
MyUserClass myObj;
if( myObj == null )
myObj = new MyUserClass();
return myObj;
}

You will end up with an "Use of unassigned local variable 'myObj'" error
when
you try to compile the code. In this case you need to set it to null.

HTH,

//Andreas
 
L

LC

Hi Bob,

Your "not actual value" state must be "null value" so you must assign null
first.

MyUserClass myObj = null;
....
if(myObj!=null){
//it has a reference to an instance
//you cant call it's members
}

LC
 
A

Andreas Håkansson

LC,

I believe we both a right, you only have to explicitly assign it null
if it has a local scope. A wider scrope will be managed by the
compiler. :)

//Andreas
 
L

LC

Andreas:

What I said is TRUE. Your field myObj is initialized to null by the
compiler. That is one of the constructor task named "variable initializers".
Reference type objects are initialized to null, bools to false, ints to
zero. Compiler does it for you.

C# especification 17.10.2 / 17.10.3

Regards,
LC
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top