Re: Getting the Type of a Generic Parameter

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Rick,

// *** Doesn't work
Type t = typeof(TDataContext);

That should work. In what way does it fail for you?

// *** doesn't work
t = TDataContext;

This wont work but also isn't needed.

// *** This is what I need to do...
TDataContext context = Activator.CreateInstance(t,connectionString);

As long as you cast the return value to the correct type that should
work too. The following simplified example compiles and runs fine for
me

class Test
{
public Test(string s)
{
Console.WriteLine(s);
}

static void Create<T>(string s)
{
Activator.CreateInstance(typeof(T), s);
}

static void Main()
{
Create<Test>("Hello World");
}
}


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
.