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.
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!)
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.
Given that an out parameter doesn't even need to be initialized by the caller, you really have to do something with it.
You could use a ref parameter instead, those don't require you to touch them in your function.
I don't like these answers telling you to use a ref
parameter as it changes the semantics of the method and will require callers to pass an initialised value.
Set result
to the default value for MinMax
, which is null
if it's a reference type, or use the default
operator.
result = default(MinMax);
The only correct way to not update an out variable is to throw an exception. Change out
to ref
.
You have to set the value of the out
variable. You could use ref
as other answers have suggested, but I wouldn't recommend it - that's not how the standard TryParse
pattern is supposed to work. Besides, it's ugly and unnecessary.
It doesn't really matter what result
contains in the failure case, since the bool
that you return indicates whether the parsing was successful or not. Just return new MinMax(0, 0)
or, if you prefer, 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;
}
精彩评论