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
NotInferno_
NotInferno_OP6d ago
Explain this to me, and break all of it down please, thanks!
Buddy
Buddy6d ago
$tryparse should give you brief information
MODiX
MODiX6d ago
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)
if (int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
if (int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
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 here
Buddy
Buddy6d ago
There 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

Did you find this page helpful?