简体   繁体   中英

Declaring a string globally in C#

In the below rough sample code of C# I have to declared a string in condition and I am unable to access it out of that brace

if(//some condition)
{
string value1 = "something";
}
//push to database value1

In the above code compiler says The name 'value1' does not exists in the current context I need the value1 to be declared in such a way that it must be accessed in whole page. I tried protected value1 but that too didn't work. I hate to use it as a separate class. Is there anyway to declare globally?

When declared within the braces, you give it scope only within the braces (aka block).

Declare it outside the braces to give it more scope.

In this example, it will be in scope within the declaring block and be available outside of the if statement:

string value1;
if(//some condition)
{
  value1 = "something";
}
//push to database value1

I suggest reading this article to understand a bit about scope in C#.

C# is block scoped, so you are defining that variable inside that if block

Proper scope examples:

string value1 = someCondition ? "something" : string.Empty;

or

string value1 = string.Empty;
if (someCondition)
{
    value1 = "something";
}

or

string value1;
if (someCondition)
    value1 = "something";
else
    value1 = string.Empty; 

You need to declare string outside the scope of if condition so that you can access it outside of if

string value1 = String.Empty;

    if(//some condition)
    {
     value1 = "something";
    }

Declare value1 outside of your conditional.

string value1;
if(//some condition)
{ 
   value1 = "something";
} 

Try this:

 string value1 = string.Empty;
 if (//condition)
     value1 = "something"

you can do like this ..

string value1= ""
if(some condition)
{
  value1 = "something";

}

I am unable to access it out of that brace

This is how C# works. Anything you define inside a pair of braces cannot exist outside of it. You must instead declate it before the brace begins.

  1. Declare the variable outside of all blocks and methods
  2. Double check to make sure you really need this to be global - This is the sanity check
  3. Set the value
  4. Null ref check if the value is not set

    //Top of page private string _value; //Block _value = condition ? "something" : null;

Now you have a nullable value to test for (null = not set) and a value that can be "globally" consumed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM