-1

I am trying to cast an object using generic arguments in C# like (foo<mypara>)obj where the mypara is a generic argument.

public class foo<T>
{
   public string name {get;set;}
    public func<T> value {get;set;}
}

var mypara = myfoo.GetType().GetGenericArguments();

where the value of mypara.Name is "int" or "string", which is actually a string representation of the type.

But how can I get the real type of mypara?

codeling
  • 11,056
  • 4
  • 42
  • 71

3 Answers3

0

A code example would be helpful, however I think all you need is obj.GetType()? That is how you get the type of an object.

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
0

You can do it like this:

if (value != null)
{
    if (value.GetType().IsGenericType == true
        && value.GetType().GetGenericArguments().Length >= 0)
    {
        IList _valuesList = null;

        if (value.GetType().GetGenericArguments()[0].ToString().ToLower().Contains("int"))
        {
            _valuesList = value as List<int>;
        }
        else if (value.GetType().GetGenericArguments()[0].ToString().ToLower().Contains("decimal"))
        {
            _valuesList = value as List<decimal>;
        }
        else if (value.GetType().GetGenericArguments()[0].ToString().ToLower().Contains("double"))
        {
            _valuesList = value as List<double>;
        }
        else if (value.GetType().GetGenericArguments()[0].ToString().ToLower().Contains("string"))
        {
            _valuesList = value as List<string>;
        }
    }
}

Ref:
Get generic instance generic type using reflection
Reflection a properties of type of generic list
Reflection and generic types

Community
  • 1
  • 1
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
0

Use reflection. GetType() on any object will get the name of the type. More reflections are necessary to make it that object type.

iefpw
  • 6,816
  • 15
  • 55
  • 79