473,699 Members | 2,383 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to find the type T of a generic.

I have a custom collection class that looks like this

public class CustomCollectio n<T> : ICollection<T>, IList<T>,
IEnumerable<T>, IDisposable, ICloneable, IComparer<T>
{....}

I need to know if the type T has implemented a certain interface
ICustomClass.

I can't do

public class CustomCollectio n<T> where T : ICustomClass,
IColltion<T>... ...

because then I would need to implement ICustomClass. I just want this
collection class to only have objects in it that implement
ICustomClass.

I figured in the constructor I could check if T is of type
ICustomClass, but I can't figure this out.

I could check when the objects are actually added, but I'd like the
check to happen right when it's created. Compile time would be best.

Any suggestions?

Nov 29 '05 #1
5 8925
You have to provide at least an implementation of the ICustomClass interface
so that you can check against it ...

public interface ICustomClass {
}

You can then check at compile time that your generic collection is being
used with objects that implement your custom interface

public class CustomCollectio n<T> : ICollection<T?, IList<T>, IEnumerable<T>,
IDisposable, ICloneable, IComparer<T>
where T : ICustomClass {

...

}

Define you actual implementation when you are ready

public class CustomObject : ICustomClass {

...

}

And the compiler with validate for you

public CustomCollectio n<CustomObject > {
}
There is no other way around it if I understand your requirement correctly!

"Narshe" <na****@gmail.c om> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I have a custom collection class that looks like this

public class CustomCollectio n<T> : ICollection<T>, IList<T>,
IEnumerable<T>, IDisposable, ICloneable, IComparer<T>
{....}

I need to know if the type T has implemented a certain interface
ICustomClass.

I can't do

public class CustomCollectio n<T> where T : ICustomClass,
IColltion<T>... ...

because then I would need to implement ICustomClass. I just want this
collection class to only have objects in it that implement
ICustomClass.

I figured in the constructor I could check if T is of type
ICustomClass, but I can't figure this out.

I could check when the objects are actually added, but I'd like the
check to happen right when it's created. Compile time would be best.

Any suggestions?

Nov 29 '05 #2
Simple : just add the following to the end of your interface list:

where T : ICustomClass

This insists that you can only create CustomCollectio n<T> instances for that
meets this contract. This also means that inside the class anything typed as
T will know that it meets the ICustomClass interface, so you will get the
intellisense etc without having to do any casting.

You could also do this at runtime with a static constuctor, but that's
harder...

Marc

"Narshe" <na****@gmail.c om> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I have a custom collection class that looks like this

public class CustomCollectio n<T> : ICollection<T>, IList<T>,
IEnumerable<T>, IDisposable, ICloneable, IComparer<T>
{....}

I need to know if the type T has implemented a certain interface
ICustomClass.

I can't do

public class CustomCollectio n<T> where T : ICustomClass,
IColltion<T>... ...

because then I would need to implement ICustomClass. I just want this
collection class to only have objects in it that implement
ICustomClass.

I figured in the constructor I could check if T is of type
ICustomClass, but I can't figure this out.

I could check when the objects are actually added, but I'd like the
check to happen right when it's created. Compile time would be best.

Any suggestions?

Nov 29 '05 #3
Thanks.

I didn't know the where clause could go after the interface list.

Nov 29 '05 #4
For completeness (going back to your original question), to get the Type of
T, just use typeof(T).

If you wanted to code it the other way (static constructor), you could get
the Type and then you can check anything about the Type that you want using
reflection; to be honest, the only time I can think of when this would be
handy is if you were happy to accept *any 1* of a set of interfaces /
base-classes, or need a particular (non-default) constructor - i.e. where
the "where" or "new" clauses don't help. As an example (based on yours, but
trimmed purely so that it compiles):

public interface ICustomClass { }
public class CustomCollectio n<T> where T : ICustomClass {
static CustomCollectio n() {
Type type = typeof(T);
if (type.GetConstr uctor(new Type[] { typeof(string) }) ==
null)
throw new NotSupportedExc eption(type.Nam e + " does not
meet the required ctor(string) signature for use in CustomCollectio n<T>");
}
}

Marc

"Narshe" <na****@gmail.c om> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
Thanks.

I didn't know the where clause could go after the interface list.

Nov 29 '05 #5
Hi,

I can think of two options:

create an instance of T
T t = new T();

ICustomClass ic = t as ICustomClass ;
if ( ic == null ) //does not implement it

The problem with the above is that you need to create an instance of T

Second variant is using reflection
Type t = typeof(T)

you can use Type.FindInterf aces or Type.GetInterfa ce

I would go for the second method

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Narshe" <na****@gmail.c om> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
I have a custom collection class that looks like this

public class CustomCollectio n<T> : ICollection<T>, IList<T>,
IEnumerable<T>, IDisposable, ICloneable, IComparer<T>
{....}

I need to know if the type T has implemented a certain interface
ICustomClass.

I can't do

public class CustomCollectio n<T> where T : ICustomClass,
IColltion<T>... ...

because then I would need to implement ICustomClass. I just want this
collection class to only have objects in it that implement
ICustomClass.

I figured in the constructor I could check if T is of type
ICustomClass, but I can't figure this out.

I could check when the objects are actually added, but I'd like the
check to happen right when it's created. Compile time would be best.

Any suggestions?

Nov 30 '05 #6

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

Similar topics

21
10660
by: Walter L. Preuninger II | last post by:
I would like to write a generic procedure that will take string or numeric variables. I can not think of a way to make this more clear except to show what I want. int main(void) { int i=7; char *s="/etc/filesystems"; generic(i);
2
15943
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code comment 1). However, if I attempt to access the dictionary by using a key object that
1
5152
by: Dotnet Gruven | last post by:
I've posted this in the adonet group, however it was suggested I might have better luck here.... ============================================================= I'm trying to use a typed dataset and ObjectDataSource binding to a SQLX db using a foreign key to filter the returned result set to display in a GridView. The error message in the subject line is generated when I try to bind the following GridView to the ObjectSource that follows...
5
8272
by: Joerg Battermann | last post by:
Hello there, I have a custom type defined via Public Class Requirement Public IDNumber As Integer Public Name As String Public Description As String Public VersionPlanAttributes As New _
5
16919
by: chellappa | last post by:
Hi All, How to find the data type of the variable ? is there any libaray function avaiable? Because i want create generic data type of some operation . Thanks All By Chellappa
9
12836
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The natural (but illegal) notation would be something like class A<QueueClasswhere QueueClass :...
5
1582
by: Random | last post by:
How can I use reflection (or some other method) to find the type of an object that has been passed in to my method under an interface definition? I try to use GetType, but that won't work.
1
1782
by: pekbob1 | last post by:
Hi Everybody I have the error (ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'UpdatePre' that has parameters: Comp, Job_Number, Request_Date, Customer, Contact_Name, Tel, Email, Media, Job_Size, Colors, Number_of_Lots, Proof, Job_Detail, PrepressID) when I tried to update the values in my dataset. (before I had the problem to Insert and Delete and I changed OldValuesParameterFormatString="original_{0}" to...
16
8939
by: vizzz | last post by:
Hi there, i need to find an hex pattern like 0x650A1010 in a binary file. i can make a small algorithm that fetch all the file for the match, but this file is huge, and i'm scared about performances. Is there any stl method for a fast search? Andrea
0
1573
by: Cirene | last post by:
Using Visual Studio I created a DataSet using the GUI (XSD file). Trying to use a tiered methodology I called the functions from my BLL. Namespace Zzz.BusinessLogicLayer #Region "DAL Access" Public Class States Public Sub New() End Sub
0
9174
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
8914
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,...
0
8883
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...
1
6534
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
5874
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
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
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
2347
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2009
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.