Create C# methods with Parameters

I have been trying to understand two code blocks. The first code block:

string status = "Healthy";

Console.WriteLine($"Start: {status}");
SetHealth(status, false);
Console.WriteLine($"End: {status}");

void SetHealth(string status, bool isHealthy) 
{
    status = (isHealthy ? "Healthy" : "Unhealthy");
    Console.WriteLine($"Middle: {status}");
}

This first code block outputs:

Start: Healthy
Middle: Unhealthy
End: Healthy

The second code block:

string status = "Healthy";

Console.WriteLine($"Start: {status}");
SetHealth(false);
Console.WriteLine($"End: {status}");

void SetHealth(bool isHealthy) 
{
    status = (isHealthy ? "Healthy" : "Unhealthy");
    Console.WriteLine($"Middle: {status}");
}

The second code block outputs:

Start: Healthy
Middle: Unhealthy
End: Unhealthy

My question is although status is set as a global variable in both the code blocks, how can SetHealth method not alter the status variable in first code block and alter the status variable in the other code block before and after SetHealth method call

The first code block sees status as a parameter and its scope is limited to the function itself. But the second code block is updating the global status variable. So, it’s all about scope.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.