473,395 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Create Generic Collection at Runtime

Is there anyway to do the following?

Type myType = typeof(User);
Collection<myType> list = new Collection<myType>();

I know I could just use User instead of myType but have a function that
takes a type and populates a collection then calls SetValue using
reflection. How would I create the generic collection to fill it and call
SetValue?

thanks
Paul
Nov 17 '05 #1
7 9097
template is called "compile-time" polymorphism, so the <myType> should
been set at "COMPILE-TIME", you can't use runtime type instead.

my suggestion is use Collection<Object>, and convert it, or just create
an Interface for your <myType>s to implement. and use
Conllection<myTypeInterface> instead.

Nov 17 '05 #2

"Paul Welter" <pw*****@loresoft.com> wrote in message
news:Oa*************@TK2MSFTNGP15.phx.gbl...
Is there anyway to do the following?

Type myType = typeof(User);
Collection<myType> list = new Collection<myType>();

I know I could just use User instead of myType but have a function that
takes a type and populates a collection then calls SetValue using
reflection. How would I create the generic collection to fill it and call
SetValue?

Why not have the function take a type parameter instead of passing it a
type?

Collection<T> CreateCollection<T>(T[] dataItems)
{
}

or what have you.
Nov 17 '05 #3
Paul Welter wrote:
Is there anyway to do the following?

Type myType = typeof(User);
Collection<myType> list = new Collection<myType>();

I know I could just use User instead of myType but have a function that
takes a type and populates a collection then calls SetValue using
reflection. How would I create the generic collection to fill it and call
SetValue?


You can do this:

Type genericType = typeof(Collection<>);
Type constructedType = genericType.MakeGenericType(myType);

Now you can create an instance of the constructed type and call methods
on it via Reflection:

object myObject = Activator.CreateInstance(constructedType, ...);
myObject.GetType().InvokeMember("SetValue", BindingFlags.Instance |
BindingFlags.InvokeMethod | BindingFlags.Public,
null, myObject, new object[] { ... });

Now finally, let me say this: I'm quite sure there should be a better
way to do whatever it is exactly that you want to do. Especially since
the advent of Generics... Think about it, or tell us about it.
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog
Nov 17 '05 #4
Type.MakeGenericType works great, thanks. Couple question about
MakeGenericType though. Is there a big performance hit for using
Type.MakeGenericType? Is the performance hit in calling
Type.MakeGenericType or when calling
Activator.CreateInstance(constructedType, ...)? Would something be gained
if I cached the Type output from the call to Type.MakeGenericType? I was
thinking something like this ...

private static Hashtable genericClassTypeCache = Hashtable.Synchronized(new
Hashtable());

private Type GetGenericClassType(Type classType, Type genericType)
{
string key = classType.ToString() + genericType.ToString();
if (genericClassTypeCache.Contains(key))
{
return (Type)genericClassTypeCache[key];
}

Type constructedType = classType.MakeGenericType(genericType);
genericClassTypeCache.Add(key, constructedType);

return constructedType;
}

thanks
Paul

"Oliver Sturm" <ol****@sturmnet.org> wrote in message
news:u9****************@TK2MSFTNGP10.phx.gbl...
Paul Welter wrote:
Is there anyway to do the following?

Type myType = typeof(User);
Collection<myType> list = new Collection<myType>();

I know I could just use User instead of myType but have a function that
takes a type and populates a collection then calls SetValue using
reflection. How would I create the generic collection to fill it and
call SetValue?


You can do this:

Type genericType = typeof(Collection<>);
Type constructedType = genericType.MakeGenericType(myType);

Now you can create an instance of the constructed type and call methods on
it via Reflection:

object myObject = Activator.CreateInstance(constructedType, ...);
myObject.GetType().InvokeMember("SetValue", BindingFlags.Instance |
BindingFlags.InvokeMethod | BindingFlags.Public,
null, myObject, new object[] { ... });

Now finally, let me say this: I'm quite sure there should be a better way
to do whatever it is exactly that you want to do. Especially since the
advent of Generics... Think about it, or tell us about it.
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog

Nov 17 '05 #5
learned a lot, thanks

Nov 17 '05 #6
Well, I'll answer this one myself. I did some simple performance testing
and found that there was no difference between caching the type and just
calling MakeGenericType every time. In the test I used 3 different generic
collection types, 8 classes to use as the generic and ran it for about 200
reps. The average time for calling MakeGenericType every time was 0.0156125
milliseconds. The average time when using the caching function below was
0.018180451 milliseconds. I guess the runtime is doing its own caching, no
need for it in this case. I would have thought there was going to be a
bigger hit then that as generics are optimized at compile time.

thanks
~ Paul

"Paul Welter" <pw*****@loresoft.com> wrote in message
news:eF**************@TK2MSFTNGP10.phx.gbl...
Type.MakeGenericType works great, thanks. Couple question about
MakeGenericType though. Is there a big performance hit for using
Type.MakeGenericType? Is the performance hit in calling
Type.MakeGenericType or when calling
Activator.CreateInstance(constructedType, ...)? Would something be gained
if I cached the Type output from the call to Type.MakeGenericType? I was
thinking something like this ...

private static Hashtable genericClassTypeCache =
Hashtable.Synchronized(new Hashtable());

private Type GetGenericClassType(Type classType, Type genericType)
{
string key = classType.ToString() + genericType.ToString();
if (genericClassTypeCache.Contains(key))
{
return (Type)genericClassTypeCache[key];
}

Type constructedType = classType.MakeGenericType(genericType);
genericClassTypeCache.Add(key, constructedType);

return constructedType;
}

Nov 17 '05 #7
Paul Welter wrote:
Well, I'll answer this one myself. I did some simple performance testing
and found that there was no difference between caching the type and just
calling MakeGenericType every time. In the test I used 3 different generic
collection types, 8 classes to use as the generic and ran it for about 200
reps. The average time for calling MakeGenericType every time was 0.0156125
milliseconds. The average time when using the caching function below was
0.018180451 milliseconds. I guess the runtime is doing its own caching, no
need for it in this case. I would have thought there was going to be a
bigger hit then that as generics are optimized at compile time.


I guess you will see a performance hit comparing this approach with the
construction of the object without Reflection. In .NET 2.0, enormous
improvements have been made to Reflection performance-wise, but it's
still slower by a huge factor.
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog
Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I...
5
by: cody | last post by:
I know I can use ArrayList.ReadOnly() to create a readonly version of it, but how can I achive a similar thing with a generic collection of .NET 2.0?
8
by: Steven Cummings | last post by:
Hello, I've scoured this usenet group and didn't find anything specific to my problem, so hopefully this won't be a repeated question. I'm all but certain it's not. I would like to *declare*...
19
by: Brett Romero | last post by:
Here's a table of data I'm putting into a collection: CodeId CodeGroup CodeSubGroup Type 1 K K.1 Shar1 2 K ...
4
by: mojeza | last post by:
I would like to create generic object which will be used for store of single row of DataTable. Lets say I create class as follow: Public Class Participant Public ParticipantID As Int64 Public...
5
by: Michi Henning | last post by:
I can pass a generic collection as ICollection<Tjust fine: static void flatCollection(ICollection<intc) {} // ... List<intl = new List<int>(); flatCollection(l); // Works fine Now I...
6
by: Venkatesh Bhupathi | last post by:
Hi All, I am trying to inherit the Generic IList<Tinterface to form the typed collection of objects of type T. Following is my sample code, Public Class Record { public string name;...
9
by: eric | last post by:
I'm trying to define a dictionary whose value is an Generic Action<> delegate private Dictionary<string, List<Action<T>>> Any ideas on to how specify T or a different collection type more...
2
by: SimonDotException | last post by:
I am trying to use reflection in a property of a base type to inspect the properties of an instance of a type which is derived from that base type, when the properties can themselves be instances of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.