473,325 Members | 2,785 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,325 software developers and data experts.

Type constraints in constructors of generic types

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){ /* */ }
}

Now, say I want to create a set for a general type and keep more
specific types in it:

Set<Fruit> fruits = new Set<Fruits>()

List<Fruit> fruitList = new List<Fruit>();
List<Apple> appleList = new List<Apple>();

fruits.AddRange(fruitList); // This is ok of course
fruits.AddRange(appleList); // This is not

This problem can be fixed by modifying the Add() method of my
collection to this

public void AddRange<U>(ICollection<U> obj) where U : T { /* */ }

Now I can do an AddRange(appleList).

So my question, is there any way to have a similar constraint in the
constructor?

class Set<T> : ICollection<T>
{
// Create set from existing collection.
public Set(ICollection<U> objs) : where U : T {/* *}
}

That would allow for this:

List<Apple> apples = new List<Apple>();
Set<Fruit> fruits = new Set(apples);

Thanks

Mar 28 '06 #1
2 2192
<an*************@gmail.com> wrote:

<snip>
So my question, is there any way to have a similar constraint in the
constructor?


Unfortunately, constructors themselves cannot be generic - i.e. you can
use the type parameter of the class you're constructing, but no other
ones.

This is just from a brief look at the spec (and a couple of failed
attempts) though - someone may jump in with a counterexample :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 29 '06 #2
Thanks Jon, I didn't think it would work, but its strange when I can so
easily replicate the behavior of such a constructor using just 3 lines
of code (a static "creator").

public static Set<T> Create<U>(ICollection<U> objs) where U : T
{
Set<T> result = new Set<T>();
result.AddRange(objs);
return result;
}

But the code would be so much nicer if it was allowed as a
constructor....

/Anders

Mar 29 '06 #3

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

Similar topics

1
by: Dmitry Martynov | last post by:
What if I have some special constructors and do not have a default constructor. It seems to be very useful when I do not want to forget to initialize some fields properly. As I have understood...
10
by: steve bull | last post by:
I have a class SwatchPanel which takes Swatch as a parameter type. How can I call a static function within the Swatch class? For example the code below fails on TSwatch.Exists. How can I get the...
4
by: Dan Krantz | last post by:
I have the following template to ensure that a given number (val) falls into a range (between vmin & vmax): template<typename T> T ForceNumericRange( const T& val, const T& vmin, const T& vmax)...
4
by: Charles Churchill | last post by:
I apologize if this question has been asked before, but after about half an hour of searching I haven't been able to find an answer online. My code is beloiw, with comments pertaining to my...
4
by: Hyun-jik Bae | last post by:
Is that not allowed to assume generic type numeric type? As far as I've tried, I got an error with the following code: public class AAA<T> { public int Foo(T a) { return a; // error: Cannot...
70
by: garyusenet | last post by:
I'm using an example piece of code: - namespace Wintellect.Interop.Sound{ using System; using System.Runtime.InteropServices; using System.ComponentModel; sealed class Sound{ public static...
5
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.
9
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to...
9
by: tadmill | last post by:
Is it possible to pass a generic parameter of the same class to to its constructor, where the "T" type passed in the constructor is different than the "T" type of the instanced class? ie, ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.