0

Compilation errors:

Visual Basic.NET Compilation error: "Type t is not defined"

C# Compilation error: 't' is a variable but is used like a type

Why i can not do this:

VB:

For i = 0 To dt.Columns.Count - 1
    Dim t As Type = dt.Columns(i).DataType
    Dim field = dt.GetValueSafely(Of t)(dt.Columns(i).ColumnName, 0) ' compilation error'
Next

C#:

for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
    Type t = dt.Columns[i].DataType;
    var field = dt.GetValueSafely<t>(dt.Columns[i].ColumnName, 0); // compilation error
}

Is there other achieve what i am trying to do or i must declare the type directly?

Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
  • 1
    Yes, you can't do that, and even if you could, what would you expect to do with `field`? In theory it could be any type. – DavidG Sep 20 '18 at 13:16
  • @HansPassant If the method wasn't generic, the error message would say that the method isn't generic. The error doesn't say that. It says that `t` is a variable, not a type, which is exactly why you can't do this. – Servy Sep 20 '18 at 13:18
  • If you declared `field` without `var` what type would you choose? – Magnus Sep 20 '18 at 13:19
  • 1
    I don't see why you need a generic in this case. Since the t can be anything, just pass object. The IDE will have no idea what to display when you do "field." – the_lotus Sep 20 '18 at 13:19

2 Answers2

0

When calling a function which uses generics, the compiler expects you to give it a class/structure name between the less/greater than symbols ('<' and '>').

You are passing it an instance variable (t) instead: this is an actual object instance, not a class/struct name, as expected by the compiler.

One way to accomplish what you intend to do is to call your GetValueSafety<T>() method through reflection. You basically retrieve the MethodInfo from the method you want to invoke by using the type of the object dt, then you specify which are the generic type parameters for this method, and then invoke it (passing the parameters you require). In your case, this would boil down to something like this:

MethodInfo method = dt.GetType().GetMethod("GetValueSafety");
MethodInfo callableMethod = method.MakeGenericMethod(t);

Object [] callParams = new Object[] { dt.Columns[i].ColumnName, 0 };
callableMethod.Invoke(dt, callParams);
vinicius.ras
  • 1,516
  • 3
  • 14
  • 28
-1

Because you use that wrong

Compiler tells you already your mistake, t is not a type but a variable

To do, what you want to archive, you need to use the actual type Type at that spot

for the reason why you cannot determine the type at runtime, there is plenty of documents out there including on SO eg. Setting generic type at runtime

X39
  • 789
  • 6
  • 22