Check if variable is defined

  • Thread starter Thread starter Wessel Troost
  • Start date Start date
W

Wessel Troost

Hi Group,

How can you check if a variable is defined in C#?

For example, "string s;" would declare an undefined variable. But how can
I check in an "if" statement wether it's defined or not?

Regards,
Wessel
 
Hi,

Your question is rather about whether a variable has been initialized. If
this is the case, you can check for default values, which are "null" for
reference types and zeroes of all kinds for value types. You won't be able
to determine though at the point of checking whether the variable in
question hasn't been initialized at all or just its value has been set back
to the initial one.
 
Hi Wessel,

Well, if the string is declared, you could check if(s == null).

Happy coding!
Morten Wennevik [C# MVP]
 
Dmitriy Lapshin said:
Hi,

Your question is rather about whether a variable has been initialized. If
this is the case, you can check for default values, which are "null" for
reference types and zeroes of all kinds for value types. You won't be able
to determine though at the point of checking whether the variable in
question hasn't been initialized at all or just its value has been set back
to the initial one.

Perhaps he was looking for something like #ifdef in C.
But I don't know if it exists in C#.
 
Wessel Troost said:
How can you check if a variable is defined in C#?

For example, "string s;" would declare an undefined variable.

Well, a variable without an assigned value.
But how can I check in an "if" statement wether it's defined or not?

You can't read it if it hasn't been definitely assigned - so the
compiler will tell you, basically.
 
Jon Skeet said:
Well, a variable without an assigned value.

Apologies - this is for local variables only. For instance and static
variables, the variable will have the default value for the type (null
in this case). There is no difference between a variable in this state
and one which has had the default value specifically assigned to it.
 
Your question is rather about whether a variable has been initialized.
If this is the case, you can check for default values, which are
"null" for reference types and zeroes of all kinds for value types.
You won't be able to determine though at the point of checking whether
the variable in question hasn't been initialized at all or just its
value has been set back to the initial one.

That works, thanks for the quick reply!

Side question: how can you asnwer so quickly? Do you get newsgroup posts
delivered by e-mail perhaps?

Greetings,
Wessel
 
We check regularly to see if there is anything new :)

Happy coding!
Morten Wennevik [C# MVP]
 

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

Back
Top