Translate

Wednesday, August 29, 2012

Variable Scope in C#

Variable Scope in C#




Variables can have one of the following levels of scope:
• Block
• Procedure
• Class
• Namespace

Block
Code:
if (sum> 100)
{
int a= sum1+sum2;
}
Here the variable a is defined inside the Block {} and it scope is inside {} and cannot access the “a” outside of the block ,if try to access will give error.





Procedure Scope

code
Internal string  GetConnection()
{
String message=”Hello Procedure Scope”;
Response.Write(message);
}
In this sample message is declared and can be used in the method GetConnection()

Class Scope

Code:
Public static class Sample{
private string myMsg;
void SetMessage ()
{
myMsg = "Hello World!";
}
void ShowMessage ()
{
MessageBox.Show(myMsg);
}
}

In this sample “myMsg” is declared inside the Sample and used in two procedures

No comments:

Post a Comment