473,893 Members | 1,660 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# typeof() and Generics

Let's say that you have:

class A
{
T DoSomething<T>( ) where T : class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}

void StartHere(Type type)
{
// And here is the problem
DoSomething<typ e>();
}
}

Any Ideas on how to call a generic function like 'DoSomething' when the calling function got the type as a parameter, not as a type parameter?

Jorge Varas

Oct 26 '06 #1
12 14914
Let's say that you have:
>
class A
{
T DoSomething<T>( ) where T : class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}
void StartHere(Type type)
{
// And here is the problem
DoSomething<typ e>();
}
}
Any Ideas on how to call a generic function like 'DoSomething' when
the calling function got the type as a parameter, not as a type
parameter?
Unfortunately, this can't be done (and I don't see how "typeof" is used here).
The closest that you could get is to make the StartHere method generic like
this:

class A
{
T DoSomething<T>( ) where T : class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}

void StartHere<T>()
{
// And here is the problem
T myValue = DoSomething<T>( );
}
}

Best Regards,
Dustin Campbell
Developer Express Inc.
Oct 26 '06 #2


"Dustin Campbell" <du*****@no-spam-pleasedevexpres s.comwrote in message news:c1******** *************** ***@news.micros oft.com...

Unfortunately, this can't be done (and I don't see how "typeof" is used here).
About the usage of typeof, here is an example of what I mean (this works):

class Program
{
static void Main(string[] args)
{
Test test = new Test();
test.CallMe();
}
}

class Test
{
public void CallMe()
{
this.DoSomethin g<Test>();
}
public void DoSomething<T>( ) where T : class, new()
{
Console.WriteLi ne(typeof(T).Fu llName);
}
}

Here I can use typeof to get the type of a Type Parameter. I was hoping that there was a way (maybe using typeof) to solve the first problem.
The closest that you could get is to make the StartHere method generic like
this:

class A
{
T DoSomething<T>( ) where T : class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}

void StartHere<T>()
{
// And here is the problem
T myValue = DoSomething<T>( );
}
}
I know, but in my case I am retrieving the type of a property using reflection, and that is the type that I need to pass to the generic DoSomething, so no point to make the initial call generic. The other option is to make a non-generic version of DoSomething and just eat the performance impact of the boxing.

Jorge Varas

Oct 26 '06 #3
You can, but you need to use reflection, which is (relatively) slow; in
particular, you would obtain the MethodInfo for the method ("GetMethod" ),
and then call MakeGenericMeth od(), which accepts the Type instances.

You would then .Invoke the returned method info.

Marc
Oct 26 '06 #4
I know, but in my case I am retrieving the type of a property using
reflection, and that is the type that I need to pass to the generic
DoSomething, so no point to make the initial call generic. The other
option is to make a non-generic version of DoSomething and just eat
the performance impact of the boxing.
If you're already using reflection, boxing should be the least of your performance
worries. :-) Second of all, the generic constraints that you've applied to
DoSomething<Ten sure that their won't be any boxing operations because only
reference types can be used with it. And finally, if you're using reflection,
you *could* use reflection to dynamically set the generic argument to your
method and invoke it like this:

using System;
using System.Reflecti on;

namespace ConsoleApp
{
class Program
{
class A
{
T DoSomething<T>( ) where T: class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}

public void StartHere(Type type)
{
MethodInfo method = this.GetType(). GetMethod("DoSo mething", BindingFlags.No nPublic
| BindingFlags.In stance);
MethodInfo closedMethod = method.MakeGene ricMethod(type) ;

object o = closedMethod.In voke(this, null);
}
}

static void Main(string[] args)
{
new A().StartHere(t ypeof(A));
}
}
}

Of course, if the "class" generic constraint isn't used, there would potentially
be boxing because the Invoke() method returns a System.Object.

Best Regards,
Dustin Campbell
Developer Express Inc.
Oct 26 '06 #5
Cool!

I was not aware of MakeGenericMeth odt. I'll give it a try.

{ ... things I have to do because C# has a very limited support for AOP }
"Marc Gravell" <ma**********@g mail.comwrote in message
news:Oq******** ********@TK2MSF TNGP03.phx.gbl. ..
You can, but you need to use reflection, which is (relatively) slow; in
particular, you would obtain the MethodInfo for the method ("GetMethod" ),
and then call MakeGenericMeth od(), which accepts the Type instances.

You would then .Invoke the returned method info.

Marc

Oct 26 '06 #6
I am caching the reflection information, but is still in reflected types
format (propertyInfo and so) so my performace is prety good (or my pc is
pretty fast, whichever is working) because I cache the information on
program start up, rather than at every call.

The boxing operation that I was worry about was going to be if I needed to
make a non-generic version (thus object type based) version of the same
function.

As I pointed out to mark, I didn't know about the "MakeGenericMet hod" usage,
so I'll give it a try.

"Dustin Campbell" <du*****@no-spam-pleasedevexpres s.comwrote in message
news:c1******** *************** ***@news.micros oft.com...
>I know, but in my case I am retrieving the type of a property using
reflection, and that is the type that I need to pass to the generic
DoSomething, so no point to make the initial call generic. The other
option is to make a non-generic version of DoSomething and just eat
the performance impact of the boxing.

If you're already using reflection, boxing should be the least of your
performance worries. :-) Second of all, the generic constraints that
you've applied to DoSomething<Ten sure that their won't be any boxing
operations because only reference types can be used with it. And finally,
if you're using reflection, you *could* use reflection to dynamically set
the generic argument to your method and invoke it like this:

using System;
using System.Reflecti on;

namespace ConsoleApp
{
class Program
{
class A
{
T DoSomething<T>( ) where T: class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}

public void StartHere(Type type)
{
MethodInfo method = this.GetType(). GetMethod("DoSo mething",
BindingFlags.No nPublic | BindingFlags.In stance);
MethodInfo closedMethod = method.MakeGene ricMethod(type) ;

object o = closedMethod.In voke(this, null);
}
}

static void Main(string[] args)
{
new A().StartHere(t ypeof(A));
}
}
}

Of course, if the "class" generic constraint isn't used, there would
potentially be boxing because the Invoke() method returns a System.Object.

Best Regards,
Dustin Campbell
Developer Express Inc.


Oct 26 '06 #7
The boxing operation that I was worry about was going to be if I
needed to make a non-generic version (thus object type based) version
of the same function.
Sure, but I assumed that you weren't going to be using value types since
you had declared the "class" generic constraint. If you have an object-type
parameter but never use a value type with it, you won't have boxing.

Best Regards,
Dustin Campbell
Developer Express Inc.
Oct 26 '06 #8
Then there is something more I need to learn... What I understand from what
you are saying is that there never is boxing between reference types? only
for value types that are used as objects?

Thus this piece of code does not do any boxing on the third line?

StringBuilder sb = new StringBuilder() ;
sb.Add("Whateve r");
object o = (object)sb;
Console.WriteLi ne(o.ToString() );

Jorge Varas

"Dustin Campbell" <du*****@no-spam-pleasedevexpres s.comwrote in message
news:c1******** *************** ***@news.micros oft.com...
>The boxing operation that I was worry about was going to be if I
needed to make a non-generic version (thus object type based) version
of the same function.

Sure, but I assumed that you weren't going to be using value types since
you had declared the "class" generic constraint. If you have an
object-type parameter but never use a value type with it, you won't have
boxing.

Best Regards,
Dustin Campbell
Developer Express Inc.


Oct 26 '06 #9
Then there is something more I need to learn... What I understand from
what you are saying is that there never is boxing between reference
types? only for value types that are used as objects?

Thus this piece of code does not do any boxing on the third line?

StringBuilder sb = new StringBuilder() ;
sb.Add("Whateve r");
object o = (object)sb;
Console.WriteLi ne(o.ToString() );
Correct.

This code:

private void Test()
{
StringBuilder sb = new StringBuilder() ;
sb.Append("What ever");
object o = (object)sb;
Console.WriteLi ne(o.ToString() );
}

Compiles to this:

..method private hidebysig instance void Test() cil managed
{
.maxstack 2
.locals init (
[0] [mscorlib]System.Text.Str ingBuilder sb,
[1] object o)
L_0000: nop
L_0001: newobj instance void [mscorlib]System.Text.Str ingBuilder::.ct or()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: ldstr "Whatever"
L_000d: callvirt instance [mscorlib]System.Text.Str ingBuilder [mscorlib]System.Text.Str ingBuilder::App end(string)
L_0012: pop
L_0013: ldloc.0
L_0014: stloc.1
L_0015: ldloc.1
L_0016: callvirt instance string object::ToStrin g()
L_001b: call void [mscorlib]System.Console: :WriteLine(stri ng)
L_0020: nop
L_0021: ret
}

This code:

private void Test()
{
int i = 1;
object o = (object)i;
Console.WriteLi ne(o.ToString() );
}

Compiles to this:

..method private hidebysig instance void Test() cil managed
{
.maxstack 1
.locals init (
[0] int32 i,
[1] object o)
L_0000: nop
L_0001: ldc.i4.1
L_0002: stloc.0
L_0003: ldloc.0
L_0004: box int32
L_0009: stloc.1
L_000a: ldloc.1
L_000b: callvirt instance string object::ToStrin g()
L_0010: call void [mscorlib]System.Console: :WriteLine(stri ng)
L_0015: nop
L_0016: ret
}

Notice the boxing operation in the second method when the Int32 is cast to
an object.


Best Regards,
Dustin Campbell
Developer Express Inc.

Oct 26 '06 #10

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

Similar topics

27
2476
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and still no can do... Any info would be great!
23
2570
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
12
2753
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as it defines the language more completely. Great to use.
9
5993
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
1
2441
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
11
12842
by: Einar Værnes | last post by:
Hi. I am trying to programatically decide which type a new object should have, but the typeof-function is apparently not the answer, as the following code will not compile. class AbstractClass:Object { } class DerivedClass1 : AbstractClass { } class DerivedClass2 : AbstractClass { }
2
3925
by: =?Utf-8?B?SmVzcGVyLCBEZW5tYXJr?= | last post by:
Hi I need to parse strings to enumerated types for several different enumerated types. Im doing this for each of them, bu I wonder if there is a way to write a generic method that also takes the specific enumerated type as an argument. Is it possible to pass the typeof(enum) as an argument, and how is it done? See current method below. regards Jesper.
13
3849
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an application that needs implementations in both Java and C#. I have the Java side done, and it works fantastic, and the C# side is nearly there. The problem I'm running into has to do with the differences in implementations of Generics between the two...
3
2087
by: Stefan Hoffmann | last post by:
hi @all, I have the following interface declaration: public interface IBaseDao<Twhere T : BasePOJO { List<TFindAll(Type entityClass); } The parameter entityClass should be typeof(T).
0
9985
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
11243
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
10839
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
9645
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5858
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
6066
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4684
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
4280
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3289
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.