Rye bread
Rye bread

Reputation: 1811

Exception when casting a generic enum parameter to nullable long

I have the following generic method where I want to encapsulate some logic that does the following: Takes an instance of ILookUp (which is my own generic interface type), if the instance is null, then call a method with a null argument, if not null, then call the same method with the value from an ID field in the interface.

The ID field is always an enum type based on ulong. The ID field is never null, still I want to cast it to a nullable type.

However, I get an InvalidCastException on the indicated statement. Strangely, in the Watch window, the cast works fine. What could be going wrong..?

   /// <summary>
   /// if not null, extracts an ID and snapshots it as a nullable ulong (ulong?)
   /// </summary>          
   public Id? SnapshotID<T, Id>(T instance)
     where T : ILookUp<T, Id>
     where Id : struct // is always an enum based on ulong
   {
      if (instance != null)
        {
            ulong? enumAsULong = (ulong?)((ValueType)instance.ID); // <- InvalidCastException here

            return (Id?)(ValueType)DoEnumNullable(enumAsULong);
        }
        else
        {
            return (Id?)(ValueType)DoEnumNullable((ulong?)null);
        }
    }

    public ulong? DoEnumNullable(ulong? val)
    {
        return DoUInt64Nullable(val);
    }

    public interface ILookUp<T,Id> 
        where T : ILookUp<T,Id>
        where Id : struct  // cannot specify enum - this allows nullable operations on       Id enums
    {

        Id ID { get; }
    }

Upvotes: 0

Views: 126

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

You can't do that. You can only cast a boxed value type to the same type or Nullable<T>. You could cast it to T? in this case Nullable<YourEnumType> but not other types.

Following should work.

ulong? enumAsULong = (ulong)((ValueType)instance.ID);

or

ulong? enumAsULong = Convert.ToUInt64((ValueType)instance.ID);

Upvotes: 1

Related Questions