473,830 Members | 2,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating T From Type

Hey,
I have the following class:

public Child<T>
{
//Some Code
}

Can I (using Reflection or any other way) create a Child object in
runtime without knowing what is T? like this:
static object GetChild(Type t)
{

}

Thanks ahead

--sternr

Mar 12 '07 #1
4 1330
On Mar 12, 11:05 am, "sternr" <Ste...@gmail.c omwrote:
Hey,
I have the following class:

public Child<T>
{
//Some Code

}

Can I (using Reflection or any other way) create a Child object in
runtime without knowing what is T? like this:
static object GetChild(Type t)
{

}
I think you'll have to use
static object GetChild<T>() : where T : new()

Mar 12 '07 #2
Hello sternr,

[TestFixture]
public class Tests {
[Test]
public void Test( ) {
Assert.AreEqual (typeof(MyClass <string>),
CreateTypeForTy pe(typeof(strin g)).GetType());
}

private object CreateTypeForTy pe(Type genericParamete r) {
Type openType = typeof(MyClass< >);
Type finalType = openType.MakeGe nericType(gener icParameter);
return Activator.Creat eInstance(final Type);
}
}

public class MyClass<T{
}
Oliver Sturm
--
http://www.sturmnet.org/blog
Mar 12 '07 #3
On Mar 12, 5:39 pm, "Oliver Sturm" <oli...@sturmne t.orgwrote:
Hello sternr,

[TestFixture]
public class Tests {
[Test]
public void Test( ) {
Assert.AreEqual (typeof(MyClass <string>),
CreateTypeForTy pe(typeof(strin g)).GetType());
}

private object CreateTypeForTy pe(Type genericParamete r) {
Type openType = typeof(MyClass< >);
Type finalType = openType.MakeGe nericType(gener icParameter);
return Activator.Creat eInstance(final Type);
}
}

public class MyClass<T{
}

Oliver Sturm
--http://www.sturmnet.or g/blog
Brilliant piece of code!
Thanks a lot Oliver!!!

--sternr

Mar 12 '07 #4
Hello sternr,
>Brilliant piece of code!
Thanks a lot Oliver!!!
Thank you, I hope it works for you.
Oliver Sturm
--
http://www.sturmnet.org/blog
Mar 13 '07 #5

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

Similar topics

1
1112
by: ChinStrap | last post by:
I am sorry if this is obvious, but I am not seeing it. How would I go about creating a new type that is of the same type as a class sent into the function? new = foo.__init__() refers to the current foo, not a new fresh instance of my class. The only way I can think of is to make a large if-elif chain of isinstances, but that loses the generality I am after. Thank you for your help.
4
561
by: Altramagnus | last post by:
I have 30 - 40 type of different window. For each type I need about 20 instances of the window. When I try to create them, I get "Error creating window handle" My guess is there is a maximum number of window handle, because if I reduce to about 2 instances of each window, it can run. But not 20 instances of each window. Does anyone know what the problem is? is it really because it exceeds the maximum number of window handle?
8
5972
by: Nanda | last post by:
hi, I am trying to generate parameters for the updatecommand at runtime. this.oleDbDeleteCommand1.CommandText=cmdtext; this.oleDbDeleteCommand1.Connection =this.oleDbConnection1; this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ApplicantName", dataset.Tables.Columns.DataType, 50,
2
4202
by: pshvarts | last post by:
(I'm new in SOAP) I get some wsdl file (from apache service ). I tried creating SOAP client with .NET - trying to add Web Reference and get error like: "Custom tool error: Unable to import WebService/Schema. Unable to import binding..." I thought may be wsdl file is not good enough (it was created with qsoap toolkit), so I paste-copy sample from http://www.w3.org/TR/2001/NOTE-wsdl-20010315#_wsdl (will paste below) and receive same error...
12
3181
by: Mats Lycken | last post by:
Hi, I'm creating a CMS that I would like to be plug-in based with different plugins handling different kinds of content. What I really want is to be able to load/unload plugins on the fly without restarting the application. What I did was to create an AppDomain that loaded the plugins and everything was great, until I tried to pass something else that strings between the domains...
17
1954
by: Lee Harr | last post by:
I understand how to create a property like this: class RC(object): def _set_pwm(self, v): self._pwm01 = v % 256 def _get_pwm(self): return self._pwm01 pwm01 = property(_get_pwm, _set_pwm)
6
1791
by: wcc | last post by:
Hello, How do I create a class using a variable as the class name? For example, in the code below, I'd like replace the line class TestClass(object): with something like class eval(className) (object):
5
3565
eragon
by: eragon | last post by:
I wrote this function to create a new file when the user posts in my forums, and its not creating a new file, can you help me? this script is not copyrighted as the last one. function createNewFile($name,$mail,$subject,$comments,$count,$date,$other="",$up="0") { global $settings; $header=implode('',file('header.txt')); $footer=implode('',file('footer.txt')); $content=' <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">...
11
3735
by: Matthew Wells | last post by:
Hello. I have figured out how to create an instance of an object only knowing the type by string. string sName = "MyClassName"; Type t = Type.GetType(sName); Object objNew = Activator.CreateInstance(t); This works, but now I need to declare an array like
19
1956
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I'm doing my c# more and more like i used to code c++, meaning i'm casting more often than creating an instance of objects. like : protected void gvOrderDetailsRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { switch (((Sale)e.Row.DataItem).SzPN) {
0
9790
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
9642
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10770
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
10481
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...
0
10199
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6948
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
5616
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...
2
3956
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3074
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.