C# - Converting String to Enumeration

Sometimes it is useful to convert a string to a value of an enumeration. It's extremely easy to convert an enumeration value to a string of course, with the ToString() method, however doing the vice versa of it doesn't seem as easy.

Searching on the net, you will find that most people create their own function, in which they will loop through all values in the enumeration, compare their string equivalent with a given string and if they are equal, the enumeration value is returned. But why do this when a method is there waiting for you on a sunbed? It is the static method Enum.Parse() which has 2 overloads.

The first overload takes the type of the enumeration and the string value, returning an object, which may often need to be cast to the type of enumeration.

Example:

enum Days {Sun, Mon, Tue, Wed, Thur, Fri, Sat };


private void main() {
  string s = "Mon";
  Days day = (Days)Enum.Parse( typeof( Days ), s );
}
The day variable will contain the enumeration value Mon.

If the given string does not exist in the enumerations, the method will raise an ArgumentException. If the string is null, the method will raise an ArgumentNullException.

Now what if in the above code, s was equal to "mon" instead of "Mon"? By default, the casing is regarded and thus, that would raise an ArgumentException. However you may use the second overload, which takes an extra boolean parameter to specify whether casing should be regarded or not.

private void main() {
  string s = "mon";
  Days day = (Days)Enum.Parse( typeof( Days ), s, true );
}
The third parameter specifies that the casing should be ignored, and thus that code is raise no exception.

All's well.

Biological Visit

Today we enjoyed the last of summer (which actually ended long ago) with a nice short swim in St. George's Bay. The next hours followed with unexpectedly heavy rain, so we sheltered until it stopped. At that point, we went back to the beach, simply to be the only persons on that sandy beach.



However, we definitely were not the only living things on the beach. Here are a list of existences that reigned on the bay:

Camouflaged Frog:


Small cockroach-looking bug:


Bigger cockroach-looking bug:


Biggest cockroach-looking bug:


Homo sapiens:

Tags: | 1 comments |