473,805 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to dynamically create generic type from other

I have some code like

if (val.GetType(). Name == typeof(List<>). Name)
{

}

which lets me determine if val is a generic list(I've already taken care of
the non-generic part but I'd rather be able to compare them like if (val is
List<>) but this obviously doesn't work. (and I can't code it for every
parameter)

But now I need to create a new type reference from val so I can use its
methods.

in the non-generic version I have

List l = new List() because I know its a list.

In the generic version I can't do this cause I don't know the generic
parameter at compile time. Something like

List<objectl = (List<object>)v al;

doesn't even work which might be ok if it did.

The code I'm using is independent of the generic parameter so it doesn't
really matter what it is(casting them to objects isn't an issue for me as
long as the type is bound to it).
Any ideas?

Thanks,
Jon
Apr 4 '08 #1
5 3638
I'd go with something like: [snip]
Note that that neither this nor your code copes with types derived from
List<T>.
OK; kinda spooky... one day I'm going to have an original thought!
Apr 4 '08 #2

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Jon Slaughter <Jo***********@ Hotmail.comwrot e:
>I have some code like

if (val.GetType(). Name == typeof(List<>). Name)
{

}

which lets me determine if val is a generic list

That's not really ideal - I don't generally like using the names of
types as points of comparison. I'd go with something like:

Type t = val.GetType();

bool isList = (t.IsGenericTyp e &&
t.GetGenericTyp eDefinition()== typeof(List<>)) ;

Note that that neither this nor your code copes with types derived from
List<T>.
>But now I need to create a new type reference from val so I can use its
methods.

in the non-generic version I have

List l = new List() because I know its a list.

In the generic version I can't do this cause I don't know the generic
parameter at compile time. Something like

List<objectl = (List<object>)v al;

doesn't even work which might be ok if it did.

I'm glad it doesn't, because otherwise you could end up adding plain
objects to a non-object List.
well, its just a reference though. It could throw and exception if you tried
to actually add them. I guess though theres no run-time way to know.
What are you actually trying to *do* with this? It's not clear what the
motivation is, so it's hard to suggest an alternative.
I'll post the code in a replay to the OP.
Apr 4 '08 #3
BTW, one way would be to create a generic list of type object and then
convert it. The objects will be of the right type but I need to somehow
convert it.

e.g., I can read ints into a List<objectwher e each object is truely an
int... but then I need to convert List<objectto List<int>
dynamically(e.g ., I don't know its an int, it could be a float or anything
else)

(heh, I'm not sure if I'm making sense here because you probably don't see
why I don't know the type parameter at compile time. I do know it but
basically the routine is suppose to work with any type parameter(or most))

Apr 4 '08 #4
Just found this on the net and seems to be exactly what I was looking for,

Type genericType = typeof(List<>);

Type constructedType = genericType.Mak eGenericType(ty peof(Int32));

Hopefully I won't have any problems with createinstance now.
Apr 4 '08 #5

"Jon Slaughter" <Jo***********@ Hotmail.comwrot e in message
news:jJ******** *****@newssvr29 .news.prodigy.n et...
Just found this on the net and seems to be exactly what I was looking for,

Type genericType = typeof(List<>);

Type constructedType = genericType.Mak eGenericType(ty peof(Int32));

Ok, that works. I'm now able to read into generic collections.
Apr 4 '08 #6

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

Similar topics

1
1842
by: Andy | last post by:
Can anyone tell me if it is possible to dynamically create generic collections? simply put I want to be able to something like this : public object test(SomeBaseClass param1) { if (param1.prop1 == "blah") { //logic to determine the type
12
2263
by: Wardeaux | last post by:
All, Wanting to find a way to create web pages to add to my website without having to recompile the codebehind everytime I want to add a new one... Here's the deal: I have a web app that takes work orders for 7 different items, each item gets 1 page for input specs. All works well. I want to add a new item. I do not want to recompile and redistribute my app everytime just to add a new input page. Can ASPX resources be compiled into a...
7
6789
by: pmclinn | last post by:
I was wondering if it is possible to dynamically create a structure. Something like this: public sub main sql = "Select Col1, Col2 from Table a" dim al as new arraylist al = LoadOracleData(sql) '____Do amazing things
4
10467
by: puzzlecracker | last post by:
I have seen these terms used in Gang of 4 but could never thoroughly understand what it meant I perceive that C++ is both, but apparently it is only a latter. Can someone explain it? thx
4
1563
by: Gazarsgo | last post by:
This seems to be a bit of a contradiction, but how can I construct a Generic class using a System.Type variable that is assigned at run time? Is there some parallel to the Generics concept that extends to having strictly-typed classes at run-time? I would gladly give up the compile-time errors if I could get rid of all these CType()s :)
1
1881
by: Lorraine | last post by:
Hi all, I have test application written in C# from which I am trying to dynamically invoke a DLL. I have two dll's the only difference being one is written in C# and the other in VB.NET. The test application is able to sucessfully invoke the dll written in C#. However when attempting to invoke the VB.NET version of the dll the following error message occurs: Unhandled Exception: System.ArgumentNullException: Value cannot be null....
9
7043
by: netasp | last post by:
hi all, how can I populate one aspx form when page is loading based on page ID? for example: loading page A (to search for VB code) would display labels and texboxes, dropdown lists all related to VB, plus the address bar would show something like this: www.somethinghere?id=3 and if you change number 3 from the address bar to (for example) 34 or 71 you would get different page with the same formatting like I.e: www.somethinghere?id=34...
15
8214
by: =?Utf-8?B?VG9tIENvcmNvcmFu?= | last post by:
I've been led to believe by several articles, particularly Eric Gunnerson's C# Calling Code Dynamically, that calling a method dynamically through Reflection was much slower than through a Delegate. My testing showed that actually it was six times faster: 0.5 seconds for 100,000 iterations versus 3.1 seconds. Can anyone explain why? Something in the way I coded it? I'd appreciate any insights. Here's the code (in a Windows Form...
4
7957
by: alan | last post by:
AFAIK a template parameter must be completely determinable by the compiler at compile time, is this correct? Currently my problem is, I have a class which contains a std::vector. The size of this vector can be determined at the time an object of the class is constructed, and is assured not to change over the lifetime of the object. Now this class is part of an intrusive memory pool management scheme, and while it's okay for the...
0
9718
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
10613
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...
0
10363
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10368
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7649
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
6876
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();...
1
4327
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
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
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.