To convert a string value to an Enum, which may be required after retrieving data from an SqlDataReader. To give more context an Order object is created/returned from a static method GetOrderByOrderId and the Order object has a property OrderStatus that is an Enum which needs to be converted as it is stored as a string variable in SQL Server database table.
Example Enum OrderStatus:
public Enum ArtifactType
{
Folder,
File
}
Order Class to represent our Order Object:
public class Order
{
public int Orderid { get; set; }
public OrderStatus OrderStatus { get; set; }
}
public static Order GetOrderByOrderId(int Orderid)
{
.....
SqlDataReader r = sqlComm.ExecuteReader();
while ( r.Read() )
{
Order o = new Order();
string orderStatus = (string)reader["OrderStatus"];
OrderStatus os = (OrderStatus) Enum.Parse(typeof(OrderStatus), orderStatus);
o.OrderStatus = os;
}
...
return o;
}
An Order object is created, then assign the OrderStatus value from the order table and assign this to a string. Next the we convert this string value "orderStatus" to the OrderStatus enum and assign to the Order object OrderStatus property.