all groups > dotnet general > february 2007 >
You're in the

dotnet general

group:

.NET Generics and Dynamic Type Assignment



.NET Generics and Dynamic Type Assignment nettellect
2/28/2007 6:48:10 AM
dotnet general: I have a simple situation in which I want to use generics along with dynamic
type assignment. Following code snippet can explain in more detail
But I am unable to do that will anybody help me why?

namespace genericTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Type X = System.Type.GetType("System.Int32");
GetMyTypes<X> a = new GetMyTypes<X>();
a.MyTypes = "Going out";
MessageBox.Show(a.MyTypes.ToString());

}
}
public class GetMyTypes<T>
{
T t;
public T MyTypes
{
get { return t; }
set { t = value; }
}
}
}


Errors
Error 1 The type or namespace name 'X' could not be found (are you missing a
Re: .NET Generics and Dynamic Type Assignment Frans Bouma [C# MVP]
3/1/2007 1:18:08 AM
[quoted text, click to view]

Using generics always has to resolve to compile time correct code,
i.e. the generic parameters have to be known at compile time. Your code
doesn't obey that, 'x' is known at runtime. That's not going to work.

So if you know 'x' at compile time (and your code does, it's an int),
specify X as int.

FB

--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
Re: .NET Generics and Dynamic Type Assignment nettellect
3/6/2007 10:41:08 PM
Agreed but what is the solution... instead of makeGenericType function

[quoted text, click to view]
AddThis Social Bookmark Button