473,804 Members | 3,019 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Create Generic Collection at Runtime

Is there anyway to do the following?

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

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 9114
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<Obje ct>, and convert it, or just create
an Interface for your <myType>s to implement. and use
Conllection<myT ypeInterface> instead.

Nov 17 '05 #2

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

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

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> CreateCollectio n<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<myTy pe> list = new Collection<myTy pe>();

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(Collecti on<>);
Type constructedType = genericType.Mak eGenericType(my Type);

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

object myObject = Activator.Creat eInstance(const ructedType, ...);
myObject.GetTyp e().InvokeMembe r("SetValue", BindingFlags.In stance |
BindingFlags.In vokeMethod | BindingFlags.Pu blic,
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.MakeGeneri cType works great, thanks. Couple question about
MakeGenericType though. Is there a big performance hit for using
Type.MakeGeneri cType? Is the performance hit in calling
Type.MakeGeneri cType or when calling
Activator.Creat eInstance(const ructedType, ...)? Would something be gained
if I cached the Type output from the call to Type.MakeGeneri cType? I was
thinking something like this ...

private static Hashtable genericClassTyp eCache = Hashtable.Synch ronized(new
Hashtable());

private Type GetGenericClass Type(Type classType, Type genericType)
{
string key = classType.ToStr ing() + genericType.ToS tring();
if (genericClassTy peCache.Contain s(key))
{
return (Type)genericCl assTypeCache[key];
}

Type constructedType = classType.MakeG enericType(gene ricType);
genericClassTyp eCache.Add(key, constructedType );

return constructedType ;
}

thanks
Paul

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

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

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(Collecti on<>);
Type constructedType = genericType.Mak eGenericType(my Type);

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

object myObject = Activator.Creat eInstance(const ructedType, ...);
myObject.GetTyp e().InvokeMembe r("SetValue", BindingFlags.In stance |
BindingFlags.In vokeMethod | BindingFlags.Pu blic,
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*****@loreso ft.com> wrote in message
news:eF******** ******@TK2MSFTN GP10.phx.gbl...
Type.MakeGeneri cType works great, thanks. Couple question about
MakeGenericType though. Is there a big performance hit for using
Type.MakeGeneri cType? Is the performance hit in calling
Type.MakeGeneri cType or when calling
Activator.Creat eInstance(const ructedType, ...)? Would something be gained
if I cached the Type output from the call to Type.MakeGeneri cType? I was
thinking something like this ...

private static Hashtable genericClassTyp eCache =
Hashtable.Synch ronized(new Hashtable());

private Type GetGenericClass Type(Type classType, Type genericType)
{
string key = classType.ToStr ing() + genericType.ToS tring();
if (genericClassTy peCache.Contain s(key))
{
return (Type)genericCl assTypeCache[key];
}

Type constructedType = classType.MakeG enericType(gene ricType);
genericClassTyp eCache.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
8875
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 want my users to be able to select a report, click on a command button on a form, which will then automatically create the report as a pdf file and save it to the user's machine. I am using Adobe Acrobat (5.0 I think) and have Adobe Distiller as a
5
3081
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
3284
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* (not just instantiate at runtime) a generic collection whose element-type is a generic class too. But I don't want to declare what the element-type's generic parameters are.
19
2338
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 K.1 MD5 3 J J.2 Shar1 I want to get the data in two ways: Codes codes;
4
2171
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 LastName As String Public FirstName As String End Class then I get a data from the database to DataTable and create array of
5
4192
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 want to pass nested collections generically:
6
4629
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; public string address;
9
6429
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 suitable to this? Thanks
2
4187
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 types derived from that base type, or arrays or generic collections of instances of types derived from that base type. All is well until I come to the properties which are generic collections, I don't seem to be able to find an elegant way of...
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10564
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7609
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5645
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4288
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2981
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.