Member-only story
3 C# keywords you need to know
Time to brush up on your C# toolbox!
As a developer, you quickly learn that the best way to keep your programming good is constantly have it grow and evolve by incorporating new tips and techniques.
And, to me, C# is one of those languages where you can constantly discover a new hidden feature that suddenly brightens your day and renews your coding habits.
So, today, I want to discuss 3 nice C# keywords that you can use to make your code more powerful and more robust: out
, ref
and in
:)
Another way to return data: the “out” keyword
When you’ve got some C# function and you want to output data from it, you usually set a return type in the prototype and write a return
statement. For example, we could make a basic square function that takes in an int and gives back an int result, like this:
int Square(int n) {
return n * n;
}
When you mix this with tuples, you can even return multiple values (which can even have different types) at once:
(int, bool) SquareWithCheck(int? n) {
if (n is int x) {
return (x * x, true);
}
return (-1, false); // n is null: cannot compute square!
}