© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
36 replies
Filomeon

String : Immutable reference type

Hello!
I don't understand something in C#, and I would love to have some guidance.
In the following code, the variable storing the string called "status" still has the value "Healthy" when outside the method scope.
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}");
}
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}");
}

Prints :
Start: Healthy
Middle: Unhealthy
End: Healthy
Start: Healthy
Middle: Unhealthy
End: Healthy


And I would love to understand why.
If the string status is passed as a reference type in the method "SetHeatlh", it means that "status" called in the method as an argument, is a variable with the address of the string "Healthy" somewhere in the Heap.
When the method says
status = (isHealthy ? "Healthy" : "Unhealthy");
status = (isHealthy ? "Healthy" : "Unhealthy");

Should it not mean that a new string with value "Unhealthy" is created on the Heap, and then the variable "status" should store the new address of this new string object in itself as a variable? Why is the address of the status not changed when we go out of the method SetHealth?
I thought any change on an reference type variable inside a method should be saved outside of this method?
Any help gladly appreciated 👍
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Why string are immutable?
C#CC# / help
4y ago
Expressing intent that method parameters are immutable for reference type arguments
C#CC# / help
3y ago
✅ reference type values are strange..
C#CC# / help
4y ago
Immutable Service Options
C#CC# / help
12mo ago