visit
/// <summary>
/// Output
/// Inside the code block: 10
/// </summary>
public static void VariableInCodeBlock()
{
bool flag = true;
if (flag)
{
int value = 10;
Console.WriteLine($"Inside the code block: {value}");
}
}
Execute the code using the main method as follows.
#region Day 2 - Variable Scope & Logic Control with Code Blocks
CodeBlocksAndScope.VariableInCodeBlock();
#endregion
// Console Output
Inside the code block: 10
/// <summary>
/// Outputs
/// Program.cs(7,46): error CS0103: The name 'value' does not exist in the current context
/// </summary>
public static void VariableOutCodeBlock()
{
bool flag = true;
if (flag)
{
int value = 10;
Console.WriteLine($"Inside the code block: {value}");
}
//Uncomment below line to validate
//Console.WriteLine($"Outside the code block: {value}");
}
Execute the code from the main method as follows.
#region Day 2 - Variable Scope & Logic Control with Code Blocks
CodeBlocksAndScope.VariableOutCodeBlock();
#endregion
// Console Output
Program.cs(7,46): error CS0103: The name 'value' does not exist in the current context
This error is generated because a variable that’s declared inside a code block is only accessible within that code block.
/// <summary>
/// Outputs
/// Program.cs(6,49): error CS0165: Use of unassigned local variable 'value'
/// </summary>
public static void VariableAboveCodeBlock()
{
bool flag = true;
int value;
if (flag)
{
//Uncomment below line to validate
//Console.WriteLine($"Inside the code block: {value}");
}
value = 10;
Console.WriteLine($"Outside the code block: {value}");
}
Execute the code using the main method as follows.
#region Day 2 - Variable Scope & Logic Control with Code Blocks
CodeBlocksAndScope.VariableAboveCodeBlock();
#endregion
// Console Output
Program.cs(6,49): error CS0165: Use of unassigned local variable 'value'
/// <summary>
/// Outputs
/// Inside the code block: 0
/// Outside the code block: 10
/// </summary>
/// <returns></returns>
public static void VariableAboveCodeBlockv1()
{
bool flag = true;
int value = 0;
if (flag)
{
Console.WriteLine($"Inside the code block: {value}");
}
value = 10;
Console.WriteLine($"Outside the code block: {value}");
}
Execute the code from the main method as follows
#region Day 2 - Variable Scope & Logic Control with Code Blocks
CodeBlocksAndScope.VariableAboveCodeBlockv1();
#endregion
// Console Output
Inside the code block: 0
Outside the code block: 10
GitHub - ssukhpinder/30DayChallenge.Net
Also published .