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
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)
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.
You can't access local variables by their name at runtime. To access members by name at runtime you can use reflection and dynamic
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With