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
ifstatement:I suggest reading this article to understand a bit about scope in C#.