Mad coder.
Mad coder.

Reputation: 2175

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?

Upvotes: 0

Views: 7962

Answers (8)

Joe
Joe

Reputation: 82634

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; 

Upvotes: 1

Oded
Oded

Reputation: 499152

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#.

Upvotes: 5

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

  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.

Upvotes: 0

Toomai
Toomai

Reputation: 4234

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.

Upvotes: 0

Glory Raj
Glory Raj

Reputation: 17701

you can do like this ..

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

}

Upvotes: 0

Tobias
Tobias

Reputation: 2985

Try this:

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

Upvotes: 0

George Johnston
George Johnston

Reputation: 32258

Declare value1 outside of your conditional.

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

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

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";
    }

Upvotes: 0

Related Questions