Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generics: Can you convert <T> ToString?

Quick one here~ I want to convert < T > ToString so I can replace the variable with that type~

public void ChangePanel<T>(T Action){

    FieldInfo Field = T.GetField(T.toString);
    Field.SetValue(SomeObject, Action);
}

Also please let me know if there is a better way to do this!!

Edit: FYI the variables in SomeObject have the same name as type

like image 817
Burdock Avatar asked Sep 23 '13 22:09

Burdock


3 Answers

You can use the typeof Keyword to get a Type instance, and the Type.Name Property to get the type's name.

public void ChangePanel<T>(T action)
{
    Type typeOfObject = someObject.GetType();
    Type typeOfAction = typeof(T);

    FieldInfo field = typeOfObject.GetField(typeOfAction.Name);
    field.SetValue(someObject, action);
}
like image 118
dtb Avatar answered Oct 01 '22 09:10

dtb


Yes. ToString() is defined on the object class which everything derives from so I would expect you can call it on any type T. However, you need to call it on the parameter itself, not the type, so rather than doing T.ToString() you should be doing Action.ToString(). If you want to get the name of the type then you should use reflection rather than ToString.

Also, the reflection options are either;

 typeof(T).Name

or

 Action.GetType().Name
like image 25
evanmcdonnal Avatar answered Oct 01 '22 09:10

evanmcdonnal


If you want to get the name of a generic type, then you can simply call typeof(T).Name:

public static string GetGenericTypeName<T>()
{
    return typeof(T).Name;
}
like image 31
Douglas Avatar answered Oct 01 '22 11:10

Douglas