473,397 Members | 1,960 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

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,TSecond>
{
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<Pair> 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 3267
Steven,
I want to declare a collection of type ICollection<Pair> 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<Pair>; 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<Pair> 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<Pair> 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,int>) pairs["my-pair-name"];

Also it would be nice if the above were legal since casting
Pair<object,object> 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<Pair> 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<IPair> 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,int>) 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,object> into whatever else isn't supposed to be legal.
foreach ( IPair pair in pairs )
Console.Writeline("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,int>)pair;
string first = typed_pair.First;
int second = typed_pair.Second;
}
}

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 FieldChangeEventArgs<T> : EventArgs
{
public T OldValue;
public T NewValue;

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

public class Field<T> : IField
{
....
public event EventHandler<FieldChangeEventArgs<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<string, IField> Fields

private void SubscribeToFieldEvents()
{
foreach (IField field in Fields)
{
field.ValueChanged += new EventHandler.....?!!
}
}
}

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

"Nima Hakami" <ca**********@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
I have a similar problem with generics:

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

public class FieldChangeEventArgs<T> : EventArgs
{
public T OldValue;
public T NewValue;

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

public class Field<T> : IField
{
....
public event EventHandler<FieldChangeEventArgs<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<string, IField> Fields

private void SubscribeToFieldEvents()
{
foreach (IField field in Fields)
{
field.ValueChanged += new EventHandler.....?!!
}
}
}

Feb 17 '06 #9

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

Similar topics

8
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; ...
2
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...
2
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...
6
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
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...
5
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...
5
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...
2
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...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...
0
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...
0
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...

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.