How can I get the output from an out parameter in C# without defining a variable to store the output?
I want to use it with:
int.TryParse()
I tried to use:
using static System.Console;
internal class Program
{
private static void Main(string[] args)
{
result => WriteLine(result + 20, double.TryParse("10", out result));
}
}
But I still need to call it in another line. Can I make it in one line for example:
using static System.Console;
internal class Program
{
private static void Main(string[] args)
{
result => int.TryParse("10", out result), WriteLine(result + 20);
}
}
>Solution :
Note that you can declare the out variable inside the function call:
bool success = int.TryParse("10", out int result);
The key point is however that int.TryParse might fail, and you don’t have anywhere you’re attempting to handle that failure. Once you put that in, the way that int.TryParse works makes more sense.
If you don’t expect the parsing to fail, you can just use int.Parse. This will return an int, and will throw an exception if parsing fails:
WriteLine(int.Parse("10") + 20);
If you want to use a default value if the parsing failed (such as 0), you can use a ternary:
WriteLine((int.TryParse("10", out int result) ? result : 0) + 20);