Ben Ben - 3 months ago 10
C# Question

Why can't I cast an integer to an enumeration

I am trying to cast an integer from a DataGridViewRow cell value which I have confirmed equals

0


AddedTask.Status = (TaskStatus) row.Cells["status"].Value;


InvalidCastException in Visual Studio

Here is the code that creates the Task object and the TaskStatus Enum.

class Task
{
public string Description { get; set; }

public TimeSpan Duration
{
get
{
if (BeginDate == DateTime.MinValue) // BeginDate has not been set
return new TimeSpan(0, 0, 0);
else if (EndDate == DateTime.MinValue)
return DateTime.Now.Subtract(this.BeginDate);
else
return this.EndDate.Subtract(this.BeginDate);
}
}

public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public TaskStatus Status { get; set; }

public Task()
{
this.Description = string.Empty;
this.BeginDate = new DateTime();
this.EndDate = new DateTime();
this.Status = TaskStatus.UNINVOICED;
}
}

public enum TaskStatus
{
UNINVOICED,
INVOICED,
PAID
}

Answer

I tested around a little bit and observed that the cast succeeds if the original value is an Int32 but fails if it is (for example) an Int64 or a byte.

My suggestes solution is to use Convert.ToInt32() before the cast:

AddedTask.Status = (TaskStatus) Convert.ToInt32(row.Cells["status"].Value);

From MSDN:

An enumeration is a set of named constants whose underlying type is any integral type. If no underlying type is explicitly declared, Int32 is used.

So your TaskStatus enum is derived from Int32 and direct casts from any other integral types will fail.