Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# possible to check if a var is defined?

Tags:

c#

I have a question: I need to check if a variable is defined in C#. I don't want to check if it is null because then I want to make this, it must exist.

e.g. I need to know it the variable string foo is defined. Is there anything like:

isDefined("foo") :: bool
like image 360
hansgiller Avatar asked May 05 '11 09:05

hansgiller


4 Answers

As you know the variable is a string, you could use String.IsNullOrEmpty(foo). This returns a bool.

If you aren't sure what type the variable is, you could use: if (foo != null)

like image 79
Neil Knight Avatar answered Oct 21 '22 04:10

Neil Knight


Can you elaborate on how you intend to use this? Based on this question and one of your previous questions, it looks like you are coming from a PHP background. In C#, there is no notion of an undefined variable. At any point in the code, a given variable is either declared or not, and you can determine whether it is declared or not simply by looking at the code. If it is not declared, the compiler will not let you use the variable at all (it doesn't exist). A variable may be declared, but uninitialized; however, the compiler will not let you read the value of the variable unless it is certain that the variable has a value. For instance:

int foo; // Declared, but uninitialized
if (bar == 42)
    foo = 3; // Initialize foo
// At this point, foo may or may not be initialized.
// Since we cannot be sure that it is initialized, 
// the next line will not compile.
x = foo;

If you want to keep track of whether or not a variable has been assigned a value (and you cannot use null to indicate that no value has been assigned), you need to keep track of this with a separate bool variable that starts out as false and is set to true when you assign to the other variable.

like image 21
Aasmund Eldhuset Avatar answered Oct 21 '22 04:10

Aasmund Eldhuset


You can't access local variables by their name at runtime. To access members by name at runtime you can use reflection and dynamic.

like image 24
CodesInChaos Avatar answered Oct 21 '22 04:10

CodesInChaos


First, declare the object with null value example:

TextBox tx = null; 

Then in the same context, you can check if the object is null to assign its type. Example:

if(tx ==null) tx = new TextBox(); 

Note: this is very useful when you are doing recursive calls to the method.

like image 28
Felipe Jimenez Avatar answered Oct 21 '22 05:10

Felipe Jimenez