Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the output directly from out parameter in C#?

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading