Useful Things to Know, #424
This is an oldie I've been meaning to post for years.
Assume a variable n of an enumerated type t. Let's say t has the traditional values Red, Blue, and Green.
n.ToString("g") produces a string equal to the name of the enumeration value: Green.
n.ToString("d") produces a string equal to the underlying value of the enumeration: 2.
Plain n.ToString() acts like n.ToString("g")
Why is this useful to remember? Because if you ever have to build a filter string in the form "ColorId = value", and your value is an instance of an enumeration, you can build the string like so:
string filter = String.Format("ColorId = {0:d}", n);
I've seen people handle this a number of ways, including casting back to Int32 and so forth, but this is definitely the shortest, tidiest way.
Assume a variable n of an enumerated type t. Let's say t has the traditional values Red, Blue, and Green.
n.ToString("g") produces a string equal to the name of the enumeration value: Green.
n.ToString("d") produces a string equal to the underlying value of the enumeration: 2.
Plain n.ToString() acts like n.ToString("g")
Why is this useful to remember? Because if you ever have to build a filter string in the form "ColorId = value", and your value is an instance of an enumeration, you can build the string like so:
string filter = String.Format("ColorId = {0:d}", n);
I've seen people handle this a number of ways, including casting back to Int32 and so forth, but this is definitely the shortest, tidiest way.
0 Comments:
Post a Comment
<< Home