Join us on the demo, while our product experts provide a detailed walkthrough of our enterprise platform.

logoAsync

The latest news in the world of engineering.

Identity and Access Management (IAM), including security and customer experience.

Visit Blog
Fuel

Grow your business to millions.Engage and retain your customers.

Visit Blog

How Enum.TryParse() works in C#

In this article, I will talk about how Enum.TryParse() works in C# and mistake which we can make while using it.

Hemant Manwani
Hemant Manwani
April 28, 2021
2 min read

Free, Secure and Trusted Way to Authenticate Your Visitors

Add login to your website in 5 minutes completely for free!

Free Sign UpNo hidden costs. No credit card needed.

Introduction

As we all know that Enums are very commonly used in the C# program. While using the Enums, we should also be aware of how the values are parsed into the Enums. In my earlier article, I have talked about the How to Use Enum in C#.In this article, I will specifically talk about the mistake we can make while using the Enum.TryParse() method.

Let's get started

As we know Enum.Tryparse() method will give us the parsed Enum. Like in the below example

public enum IdentityProtocols
{
    SAML,
    OAuth,
    OpenID
}
var isEnumParsed=Enum.TryParse("0", true, out IdentityProtocols parsedEnumValue);
Console.WriteLine(isEnumParsed?parsedEnumValue.ToString():"Not Parsed");

The above code will print the SAML because the enum is started by default with the value 0.

What happens if we run the below code with the same Enum declaration?

var isEnumParsed=Enum.TryParse("-1", true, out IdentityProtocols parsedEnumValue);
Console.WriteLine(isEnumParsed?parsedEnumValue.ToString():"Not Parsed");

As per our understanding isEnumParsed variable should be false, and the above code should print Not Parsed as the value which we are passing in the method is not in the Enum declaration, right?

But here is a catch, isEnumParsed variable have the true value, and the code will print -1.

Why Enum.tryParse() parse int values?

The default type of Enum in C# is int. That's why any valid integer values are parsed by the Enum.TryParse() method irrespective of those integer values are defined in the Enum or not.

We can define the Enum with types like byte, sbyte, etc. Then the Enum.TryParse() will parse those values which will fall in that defined Enum type.

How to overcome this behavior of Enum.TryParse()

To overcome this behavior of Enum.TryParse() we can follow the below approaches.

1. Using Enum.IsDefined() method with Enum.TryParse() method

var isValidEnum = Enum.TryParse("-1", true, out IdentityProtocols parsedEnumValue) && Enum.IsDefined(typeof(IdentityProtocols), parsedEnumValue);
Console.WriteLine(isValidEnum ? parsedEnumValue.ToString(): "Not Parsed");

In the above code Enum.IsDefined() will check that the value which we are getting from the Enum.TryParse() method is defined in the Enum declaration or not.

That will give us the proper result, and the above code will print Not Parsed

2.Using Enum.GetNames() method

var value = "-1";
var identityProtocolsList = Enum.GetNames(typeof(IdentityProtocols)).ToList();
Console.WriteLine(identityProtocolsList.Contains(value) ? value : "Not Parsed");

In this code, checking that value is present or not by getting all the Names from the enum declaration by using Enum.GetNames() method.

This code will print Not Parsed

Note: Here, we will not be able to parse any of the integer values. It will only check the values which are defined in the Enum declaration.

Conclusion

In this article, We have discussed the mistake we can make using the Enum.TryParse() method. This mistake can hurt and can abnormally terminate our program/application. We can use the ways I have mentioned in this article to overcome so that our program/application can run smoothly.



LoginRadius Docs

Implement Authentication in Minutes

click here

Most Popular Tags

EngineeringJavaScriptReactNodeJsAuthenticationCSSSecurityOAuthC#Go

Are your customers safe on your application?

According to Forbes, data breaches exposed 4.1 billion records in the first six months of 2019. If this gets you worried, we’ve got your back!

LoginRadius protects your customers’ identities. We provide world-class security for your customers during login, registration, password setup, and any other data touchpoints, and make sure that their data is safe. We do so through by offering open source SDKs, integrations with over 150 third party applications, pre-designed and customizable login interfaces, and best-in-class data security products such as MFA, RBA, and Advanced Password Policies. The platform is already loved by over 3,000 businesses with a monthly reach of 1.17 billion users worldwide.Secure Your Application Now

Hemant Manwani

Hemant Manwani

Hemant Manwani is a Software Engineer at LoginRadius who is interested in how the web works and developer tools that make working with web easier.

View Profile

Try a Modern Authentication Solution

$0/ month

Free Sign Up
  • 7,000 Monthly Active Users
  • 1 Web or Mobile App
  • Email/Password Login
  • 3 Social Login Providers
  • User Data Storage
  • Transactional Email Template
  • Customizable Login Interfaces