Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to not update an out variable

Tags:

c#

I've implemented a TryParse function for a class MinMax like this:

    public static bool TryParse(string s, out MinMax result)
    {
        var parts = s.Split(' ');
        if (parts.Length != 2)
        {
            return false;
        }
        float min;
        float max;
        if (!float.TryParse(parts[0].Trim(), out min) || !float.TryParse(parts[1].Trim(), out max))
        {
            return false;
        }
        result = new MinMax(min, max);
        return true;
    }

However this doesn't compile since apparently the out parameter needs to be written. What's the correct way to fix this? I would like to be able to use the function so that if the parsing fails, the parameter passed into it remains unchanged. I guess one way would be to add something like:

result = result;

but this line issues a warning.

like image 235
Andreas Brinck Avatar asked Jan 26 '26 05:01

Andreas Brinck


2 Answers

Pass by ref:

public static bool TryParse(string s, ref MinMax result) 

which means you will have to ensure the result parameter is initialised.

Update: It is better to stick to the well known semantics of TryParse. (I'm sometimes critised for answering the real question not the one that was asked! On this occasion it was the opposite!)

like image 184
Mitch Wheat Avatar answered Jan 27 '26 19:01

Mitch Wheat


Assuming MinMax is a reference type, just assign null to it. Just like any other TryParse method would work.

Check out this code:

    string s = "12dfsq3";
    int i = 444;
    int.TryParse(s, out i);
    Console.WriteLine(i);

i will be set to 0 instead of remaining at 444.

like image 32
Gerrie Schenck Avatar answered Jan 27 '26 20:01

Gerrie Schenck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!