Search code examples
c#asp.netparametersreferencedirectcast

ASP.NET C# Error: The Type must be a reference type in order to use it as parameter 'T' in the generic type or method


I have a class: Constants.cs

Code:

namespace DataAccess.Utilities
{
  public class Constants
  {
    public enum ReturnCode
    {
      Fail = -1,
      Success = 0,
      Warning = 1
    }
  }
}

This is my code for directcast class

public static T DirectCast<T>(object o) where T : class
{
    T value = o as T;
    if (value == null && o != null)
    {
        throw new InvalidCastException();
    }
    return value;
}

Here is my code that get's error

code = DirectCast<Constants.ReturnCode>(int.Parse(db.GetParameterValue(command, "RESULTCODE").ToString().Trim()));

Error Message:

Error 2 The type 'DataAccess.Utilities.Constants.ReturnCode' must be a reference type in order to use it as parameter 'T' in the generic type or method 'DataAccess.DataManager.QueueingManager.DirectCast(object)'

Before I am using DirectCast from .net vb, but DirectCast is not exist in c# so I try searching and I get some codes on how to create DirectCast that has same function to vb.


Solution

  • code = DirectCast<Constants.ReturnCode>(int.Parse(db.GetParameterValue(command, "RESULTCODE").ToString().Trim()));
    

    Should be changed to:

    code = DirectCast<Constants>(int.Parse(db.GetParameterValue(command, "RESULTCODE").ToString().Trim()));
    

    Or, do it like this: see working example:

    class Program
    {
        static void Main(string[] args)
        {
            var fail = Constants.DirectCast<Constants.ReturnCode>(-1);
            var success = Constants.DirectCast<Constants.ReturnCode>(0);
            var warning = Constants.DirectCast<Constants.ReturnCode>(1);
            Console.WriteLine(fail);
            Console.WriteLine(success);
            Console.WriteLine(warning);
            Console.ReadLine();
        }
    }
    
    public class Constants
    {
        public enum ReturnCode
        {
            Fail = -1,
            Success = 0,
            Warning = 1
        }
    
        public static T DirectCast<T>(object o)
        {
            T value = (T)o;
            if (value == null && o != null)
            {
                throw new InvalidCastException();
            }
            return value;
        }
    }