What is the correct way not to update the out variable

I implemented a function TryParsefor the class MinMaxas follows:

    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 does not compile, since, apparently, the out parameter should be written. What is the right way to fix this? I would like to be able to use the function so that when parsing the parameter passed to it remains unchanged. I guess one way would be to add something like:

result = result;

but this line gives a warning.

+3
source share
6 answers

Assuming MinMax is a reference type, just set it to zero. Like any other TryParse method.

Check this code:

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

i will be set to 0, not 444.

+2

:

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

, result.

: TryParse. ( , , ! !)

+3

, out, - .

ref, .

+2

out - . out ref.

+1

, ref, .

result MinMax, null, , default.

result = default(MinMax);
+1

out. ref, , - , TryParse. , .

, result , bool , . new MinMax(0, 0) , , default(MinMax):

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

    result = default(MinMax);    // or just use "result = new MinMax(0, 0);"
    return false;
}
0

Source: https://habr.com/ru/post/1775161/


All Articles