C # can check if var is defined?

I have a little question, I need to check if var is defined in C #. I do not want to check if it is null, because then I want to do this, it must exist.

eg. I need to know that it is defined as var string foo , is there something like:

 isDefined("foo") :: bool 
+6
source share
4 answers

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

If you don't know what type of variable you can use: if (foo != null)

+7
source

Can you talk about how you are going 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 concept of an undefined variable. At any point in the code, the given variable is declared or not, and you can determine whether it is declared or not by simply looking at the code. If it is not declared, the compiler will not allow you to use the variable at all (it does not exist). A variable can be declared, but not initialized; however, the compiler will not allow you to read the value of a variable unless you are sure 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 track whether a variable has been assigned a value (and you cannot use null to indicate that a value has not been assigned), you need to track this with a separate bool that starts with false and sets to true when you assign another a variable.

+4
source

You cannot access local variables by name at run time. You can use reflection and dynamic to access members by name at run time.

+1
source

Source: https://habr.com/ru/post/887354/


All Articles