Last active
January 22, 2020 11:18
-
-
Save jorgecolonconsulting/6d98a57b68d849ee7091 to your computer and use it in GitHub Desktop.
C# ref vs out in function/method parameter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string message = "hello"; | |
public void SayMessage(ref string message) { | |
Console.WriteLine(message); | |
message = "hello in here"; | |
} | |
SayMessage(ref message); // "hello" | |
Console.WriteLine(message); // "hello in here" | |
// run this code: http://csharppad.com/gist/ca901eb8e7d995a1f29c |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string message = "hello"; | |
public void SayMessage(out string message) { | |
message = "hello in here"; | |
Console.WriteLine(message); | |
} | |
SayMessage(out message); // "hello in here" | |
Console.WriteLine(message); // "hello in here" | |
// run this code: http://csharppad.com/gist/8e4c1dd9b153b3ef7d8f |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string message = "hello"; | |
public void SayMessage(out string message) { | |
Console.WriteLine(message); // (4,23): error CS0269: Use of unassigned out parameter 'message' | |
message = "hello in here"; | |
} | |
SayMessage(out message); | |
Console.WriteLine(message); | |
// run this code: http://csharppad.com/gist/8e4c1dd9b153b3ef7d8f |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string message = "hello"; | |
public void SayMessage(string message) { | |
message = "hello in here"; | |
Console.WriteLine(message); | |
} | |
SayMessage(message); // "message" | |
Console.WriteLine(message); // "message" | |
// run this code: http://csharppad.com/gist/8e4c1dd9b153b3ef7d8f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I stumbled upon this on Stack Overflow. Unfortunately my rep is too low to comment or upvote. I just wanted to say that it is a fantastic example and clarifies things nicely for me. Many thanks!