Home > Net >  Casting object to type variable inside method
Casting object to type variable inside method

Time:10-20

I have the below extension method where I pass the type and cast the object to the type but get a compile error at casting.

public static void AddCellProperties(this ColumnInfo _columnInfo, Type type)
{
    _columnInfo.SetCellUsing((c, o) =>
               {
                   if (o == null) c.SetCellValue("NULL");
                   else c.SetCellValue((type)o); // getting an error here near "type"
               })
               .SetPropertyUsing(a => a as string == "NULL" ? null : Convert.ChangeType(a, type, CultureInfo.InvariantCulture));
}

But whereas this works.

public static void AddCellProperties(this ColumnInfo _columnInfo)
{
    _columnInfo.SetCellUsing((c, o) =>
               {
                   if (o == null) c.SetCellValue("NULL");
                   else c.SetCellValue((int)o);
               })
               .SetPropertyUsing(a => a as string == "NULL" ? null : Convert.ChangeType(a, typeof(int), CultureInfo.InvariantCulture));
}

I am just trying to replace the int with type so that caller can pass whatever type.

Could anyone please let me know how I can overcome this issue? Thanks in advance!!!

CodePudding user response:

The short answer is that T could be any type, not simply int. If any of those types would produce a compile time error, you'll see it.

This article explains in more detail: https://ericlippert.com/2015/10/14/casts-and-type-parameters-do-not-mix/#more-2852

Are you sure you want to be able to pass in any generic type to cast your data to? Will your data cleanly cast to any type provided?

CodePudding user response:

You cannot typecast using your type variable in this manner. That is why you are getting an error on the line you have commented. If the type expected by SetCellValue is always int then it doesn't really make sense to try to typecast it to type since it is expecting int. Instead, use the same Convert.ChangeType method.

  • Related