1

I have something like this

public void FunctionName<T>(){

}

and to call this you need something like this

sub main(){
    FunctionName<Integer>();
}

my question is can i pass the Integer as "Integer"?

sub main(){
    FunctionName<"Integer">();
}

or is there any other way to that

Ok here is my actual code

private static T Convert<T>(DataRow row) where T : new()
{
    T model = new T();
    Type modelType = model.GetType();
    FieldInfo[] fields = null;
    FieldInfo field = default(FieldInfo);
    Type fieldType = null;
    string fieldName = null;

    fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);

    foreach ( field in fields) {
        fieldType = field.FieldType;
        fieldName = field.Name.Replace("_", string.Empty);
        Interaction.CallByName(model, fieldName, Microsoft.VisualBasic.CallType.Set, GetValue(row, fieldName, fieldType.Name));
    }

    return model;
}


static void main(){
    Student s;

    s = Convert<Student>(DatabaseRow);
}

The problem here is I just can only get the Student as string ("Student") from somewhere that will use this code Any other solution to get this right?

valrecx
  • 459
  • 5
  • 19

3 Answers3

6

Without seeing more of your code, it's hard to say for sure whether you have a legitimate use-case for invoking a method like this. But regardless, assuming FunctionName is contained in class Foo, then you can invoke the method using reflection:

var foo = new Foo();
var typeName = "System.Int32";
var method = typeof(Foo).GetMethod("FunctionName");
var genericMethod = method.MakeGenericMethod(Type.GetType(typeName));
genericMethod.Invoke(foo, new Type[0]);

Note that we can't use Integer since that's not the real type name. (it's either int or Int32 in C# but only Int32 is legal for GetType since int is baked into the compiler) Also, all the usual caveats about getting a type via Type.GetType apply here (there are many situations where it won't find your custom type).

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
4

No, you can't do that. You should use generics only if the type is known at compile-time. That's the whole point of generics: enforce compile-time safety. If the type is not known at compile-time, as in your case, you could use Reflection or some other technique depending on what you are trying to achieve.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thats what I'm trying to do. Use Reflections to call the function but that technique returns the classname as string instead of the actual class type – valrecx Aug 05 '12 at 16:55
0

In additin to Darin's answer: If the function was not compiled for the specified type (simply because it's never explicitely called for this type), the code is not available at all.

Serge Wautier
  • 21,494
  • 13
  • 69
  • 110