0

I'm using LINQ to Entities to generate typed result sets in VB.Net. I've got a generic Report class as follows:

Public Class Report
    Public Property Name As String
    Public Property SQL As String
    Public Property Type As String
End Class

Then in the calling scope I want to have code that does something like:

' create my data context
Dim context As New MyAppEntities
' get a report object out of a dropdown list
Dim rpt as Report = CType(aComboBox.SelectedItem, Report)
' create a result object based on the type stored in the object
Dim res As ObjectResult(Of rpt.Type) = context.ExecuteStoreQuery(Of rpt.Type)(rpt.SQL)

So far I'm finding that .Net won't let me set the type in the (Of Type) clause on the fly at runtime.

Does anyone know how to do this?

I've tried changing the Type property of the Report class to an object of type Type, but that doesn't work either.

BTW, I know there are alternative ways to accomplish the same thing, but I'm working with external constraints that make this what I've got to work with right now. And anyway, intuitively something like this should work and I'd like to figure out how.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
morphatic
  • 7,677
  • 4
  • 47
  • 61
  • Are you trying to dynamically specify a generic type parameter? I think you'll need to use reflection for that. See http://stackoverflow.com/questions/196936/reflection-and-generic-types. – Jim Mischel Oct 10 '11 at 17:48

2 Answers2

1

Here's the answer in C#:

Creating a Generic<T> type instance with a variable containing the Type

The relevant methods and code:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);

In this case, you'd use ObjectResult instead of List. Hope that helps.

Community
  • 1
  • 1
Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
0

With option strict on you can't do that. Strict enforces static typing. With static typing you'll have to stick with Object but if you remove the strict option you can accomplish dynamic typing in vb.net see this question

Community
  • 1
  • 1
Rune FS
  • 21,497
  • 7
  • 62
  • 96