Enum.TryParse: Is there a guarantee or contract for the out parameter value when the return value is `false`?

StackOverflow https://stackoverflow.com/questions/12357689

Вопрос

According to the documentation for Int32.TryParse, if the method returns false, it will set the out parameter to zero. I do not see a similar guarantee for Enum.TryParse in its documentation. It seems that there ought to be such a guarantee, because the method has to set the out parameter to something, and zero makes the most sense.

Is the guarantee specified or documented somewhere else, or is there really no guarantee?

Это было полезно?

Решение

I don't expect it to be guaranteed to be be anything more specific than "something". Since documentation does not specify otherwise (and it is the only official documentation) just use return value, but ignore out parameter if return is false.

Side note: I think it is wrong that Int32.TryParse specifies what out parameter is set to if parsing failed as one should make own decisions what "not really a number" means in each particular case... But it is my personal opinion.

Другие советы

According to MSDN

If value is a name that does not correspond to a named constant of TEnum, the method returns false. If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

So I would absolutely NOT rely on the value of out in case the call comes back with false!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top