What is: if (Enum.TryParse<PlayerRole>(playerResponse, true, out PlayerRole selectedRole))
Hello! I'm new to C#, I have a question what is if (Enum.TryParse<PlayerRole>(playerResponse, true, out PlayerRole selectedRole)), thanks!
4 Replies
Explain this to me, and break all of it down please, thanks!
$tryparse should give you brief information
When you don't know if a string is actually a number when handling user input, use
int.TryParse
(or variants, e.g. double.TryParse
)
TryParse
returns a bool
, where true
indicates successful parsing.
- Avoid int.Parse
if you do not know if the value parsed is definitely a number.
- Avoid Convert.ToInt32
entirely, this is an older method and Parse
should be preferred where you know the string can be parsed.
Read more hereThere are different types that has TryParse but it ultimately does the same
It tries to parse for example a string into a certain type (in your case it would be PlayerRole), and gives a boolean whether it was successfully parsed into said boolean, and the out parameter is set to the parsed value.
So in your case if
TryParse
returns true
and say input was Administator
the selectedRole
would then be equal to PlayerRole.Administrator
If TryParse
had failed then it would've returned false
and selectedRole
would have the default value of PlayerRole