473,791 Members | 3,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic Collection of deferred generic types

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.

My best example is using the common "Pair" example. Suppose you have
the following:

public struct Pair<TFirst,TSe cond>
{
public TFirst FirstValue;
public TSecond SecondValue;
}

Granted in my implementation I'm declaring a class, and I understand
struct is a value-type, so I don't know if this has any effect on my
problem, but onward...

I want to declare a collection of type ICollection<Pai r> such that I
can put Pair<string,int > or Pair<uint,int> in it. I need type Pair to
be generic, but I need my collection to not care about that just yet.
The quick and dirty solution would be to not use generics for the
collection and always cast both ways, but I was wondering if anybody
could think of a better solution?

Thanks.

Jan 17 '06 #1
8 3283
Steven,
I want to declare a collection of type ICollection<Pai r> such that I
can put Pair<string,int > or Pair<uint,int> in it. I need type Pair to
be generic, but I need my collection to not care about that just yet.
The quick and dirty solution would be to not use generics for the
collection and always cast both ways, but I was wondering if anybody
could think of a better solution?


The solution is probably to move any members in Pair that you need to
use in the collection to a non-generic base class or interface that
Pair then extends (impossible in this case since it's a struct) or
implements.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Jan 17 '06 #2
The ICollection must be typed to something, and since Pair<Class1> and
Pair<Class2> cannot cast to eachother, I can think of 2 immediate solutions:

1: base class (here using class; not sure if it would work using struct)

public class Pair {}
public class Pair<T1, T2> : Pair {} // the typed class has the properties
etc

Now you can create an ICollection<Pai r>; note that it won't have much on it,
though!

2: interface

public interface IPair {}
public class Pair<T1,T2> : IPair {}

But I don't think you gain much by doing it as neither Pair nor IPair have
any interesting properties! You might as well use object (except at least
the first option ensures the type hierarchy)

Better options may be available
Jan 17 '06 #3
Thanks for the responses. Those are some of the various things I had in
mind for alternatives, but the more reading I do, the more it seems I
won't be able to get *exactly* what I'm looking for here. Not the end
of the world, just won't be able to strongly type the collection.

Jan 18 '06 #4


Steven Cummings wrote:
Thanks for the responses. Those are some of the various things I had in
mind for alternatives, but the more reading I do, the more it seems I
won't be able to get *exactly* what I'm looking for here. Not the end
of the world, just won't be able to strongly type the collection.
You earlier wrote:
I want to declare a collection of type ICollection<Pai r> such that I
can put Pair<string,int > or Pair<uint,int> in it. I need type Pair to
be generic, but I need my collection to not care about that just yet.
The quick and dirty solution would be to not use generics for the
collection and always cast both ways, but I was wondering if anybody
could think of a better solution?


I don't see how it would ever be possible to strongly type the
collection down to the types of elements of the Pair, since you want
those to be variadric.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Jan 19 '06 #5
Well, the idea I had is that it would be nice to have to typing force
that the elements must be Pairs. So If I have

ICollection<Pai r> pairs = .... initialization .... // And this
currently can't be done.

I would still have to cast what I got out of the collection down to the
specific Pair implementation, but I still had the benefit of at least
enforcing that the elements be pairs.

Pair<string,int > pair = (Pair<string,in t>) pairs["my-pair-name"];

Also it would be nice if the above were legal since casting
Pair<object,obj ect> into whatever else isn't supposed to be legal.

I could use the subclassing mechanism, where something like PairBase
doesn't have the generics, but that seems a hefty kludge to impose on
your model just for this benefit, so it's not worth it in the end.
That's all. Like I said, not the end of the world. I'm still somewhat
new to C#'s generics, so I'm in the mode of testing it's limits.

Jan 19 '06 #6


Steven Cummings wrote:
Well, the idea I had is that it would be nice to have to typing force
that the elements must be Pairs. So If I have

ICollection<Pai r> pairs = .... initialization .... // And this
currently can't be done.
Actually, that's almost what Marc Gravell suggested, isn't it?

I haven't compiled the following code, but it should (roughly) work:

public interface IPair {
object First { get; set; }
object Second { get; set; }
}
public struct Pair<T,R>: IPair {
public new T First;
public new R Second;
public Pair(T first, R second)
{ this.First = first; this.second = Second; }
public IPair.First {
get { return First; }
set { First = (T)value; }
}
public IPair.Second {
get { return Second; }
set { Second = (R)value; }
}
}

ICollection<IPa ir> pairs =
new ArrayList<IPair >(
new IPair[] {
new Pair<string, int>("0", 0),
new Pair<int, string>(0, "0")
});
pairs.Add(new Pair<string,int >(1, "1"));
I would still have to cast what I got out of the collection down to the
specific Pair implementation, but I still had the benefit of at least
enforcing that the elements be pairs.

Pair<string,int > pair = (Pair<string,in t>) pairs["my-pair-name"];
ICollection<T> doesn't have an indexer, it has a .Contains, though.

Perhaps you are looking for an IDictionary instead? You could make a
helper-class for indexing like the above, but if you need to index by
the First property, perhaps you are better off using one of the
IDictionary implementations .
Also it would be nice if the above were legal since casting
Pair<object,obj ect> into whatever else isn't supposed to be legal.
foreach ( IPair pair in pairs )
Console.Writeli ne("Got pair {0},{1}", pair.First, pair.Second);
if ( pair is Pair<string,int > ) {
object old_first = pair.First;
pair.First = "x";
Pair<string,int > typed_pair = (Pair<string,in t>)pair;
string first = typed_pair.Firs t;
int second = typed_pair.Seco nd;
}
}

Should be legal, and run as expected.
I could use the subclassing mechanism, where something like PairBase
doesn't have the generics, but that seems a hefty kludge to impose on
your model just for this benefit, so it's not worth it in the end.
That's all. Like I said, not the end of the world. I'm still somewhat
new to C#'s generics, so I'm in the mode of testing it's limits.


Introducing a common super-type is the usual trick for getting
compile-time typed languages to do this kind of thing.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Jan 19 '06 #7
I have a similar problem with generics:

I have a generic class Field<T> which includes an event like this:

public class FieldChangeEven tArgs<T> : EventArgs
{
public T OldValue;
public T NewValue;

public FieldChangeEven tArgs(T oldValue, T newValue)
{
OldValue = oldValue;
NewValue = newValue;
}
}

public class Field<T> : IField
{
....
public event EventHandler<Fi eldChangeEventA rgs<T>>
ValueChanged;
}

Now I've also a class called Entity which includes a dictionary
collection of fields. Assuming that the previous workaround help
getting the collection work fine, I still don't know how I could use
that event-handler here in the Entity class: I want to subscribe to the
FieldChanged event of all those fields in the Entity and fire an
EntityChanged event whenever a field changes.

public class Entity
{
public Dictionary<stri ng, IField> Fields

private void SubscribeToFiel dEvents()
{
foreach (IField field in Fields)
{
field.ValueChan ged += new EventHandler... ..?!!
}
}
}

Feb 17 '06 #8
And IField is............. ..?

"Nima Hakami" <ca**********@g mail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
I have a similar problem with generics:

I have a generic class Field<T> which includes an event like this:

public class FieldChangeEven tArgs<T> : EventArgs
{
public T OldValue;
public T NewValue;

public FieldChangeEven tArgs(T oldValue, T newValue)
{
OldValue = oldValue;
NewValue = newValue;
}
}

public class Field<T> : IField
{
....
public event EventHandler<Fi eldChangeEventA rgs<T>>
ValueChanged;
}

Now I've also a class called Entity which includes a dictionary
collection of fields. Assuming that the previous workaround help
getting the collection work fine, I still don't know how I could use
that event-handler here in the Entity class: I want to subscribe to the
FieldChanged event of all those fields in the Entity and fire an
EntityChanged event whenever a field changes.

public class Entity
{
public Dictionary<stri ng, IField> Fields

private void SubscribeToFiel dEvents()
{
foreach (IField field in Fields)
{
field.ValueChan ged += new EventHandler... ..?!!
}
}
}

Feb 17 '06 #9

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

Similar topics

8
1833
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
2
2228
by: anders.forsgren | last post by:
I have a generic collection looking like this Set<T> : ICollection<T> { // Create set from existing collection. public Set(ICollection<T> objs) {/* */} // Add objects to set public void AddRange(ICollection<T> objs){ /* */ } }
2
1722
by: cylt | last post by:
Hi, I would like to have something like that : IList<IUser> list2 = list1 as IList<IUser>; where list1 is a generic collection of User ( IList list1<User>=new List<User>() ) and where User implement the interface IUser. But this did not work... I thought that as User implement IUser it was possible to cast the generic
6
7663
by: Jorge Varas | last post by:
Hi all, Is it possible to have a collection of a generic type? for example: class a<twhere t : class, new { }
2
1490
by: Angel Mateos | last post by:
I have this structure: Class ElemBase Class Elem1 : Inherits ElemBase Class ColecBase(Of GenElem As {ElemBase, New}) : Inherits System.ComponentModel.BindingList(Of GenElem) Class Colec1 : Inherits ColecBase(Of Elem1)
5
1869
by: Ethan Strauss | last post by:
Hi, I have just started using Generic Collections for .Net 2.0 and so far they are working very nicely for me. But, I do have a couple of questions. If I have a Generic collection which has a type which is a reference type, is there a way to get Collection.ContainsKey(RefKey) and Collection to work with different instances of equal keys? For example, I have defined a class of "codon" and I have made a dictionary private...
5
4191
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:
2
2727
by: mironline | last post by:
dear friends I have a problem with generic collection with anonymous types; my code is : public class BASE { public List<????> CreateCollection(){ List<????> x = new List<????>;
2
4186
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
9669
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
9517
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
10428
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
10207
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
10156
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
9997
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
5435
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
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

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.