Home All Groups Group Topic Archive Search About

Subject: .NET Generics and Dynamic Type Assignment

Author
28 Feb 2007 2:31 PM
nettellect
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?)

Author
28 Feb 2007 2:43 PM
Jon Skeet [C# MVP]
nettellect <nettell***@discussions.microsoft.com> wrote:
> 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?

To make a generic type with a type only known at runtime, you need to
get the generic version of the type, then call Type.MakeGenericType.

However, at that point it's pretty hard to use.

What are you actually trying to do?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Author
28 Feb 2007 3:19 PM
nettellect
well I will try to do it... I am trying to develop some sort of rules
designer in WF using winfx 3.0 so a situation came where I was in need of
this solution to keep my code simple and readable.

Show quote
"Jon Skeet [C# MVP]" wrote:

> nettellect <nettell***@discussions.microsoft.com> wrote:
> > 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?
>
> To make a generic type with a type only known at runtime, you need to
> get the generic version of the type, then call Type.MakeGenericType.
>
> However, at that point it's pretty hard to use.
>
> What are you actually trying to do?
>
> --
> Jon Skeet - <sk***@pobox.com>
> http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
> If replying to the group, please do not mail me too
>

AddThis Social Bookmark Button