.NET Generics and Dynamic Type Assignment

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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
using directive or an assembly reference?)
 
nettellect said:
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 using directive or an assembly reference?)

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#)
------------------------------------------------------------------------
 
Back
Top