473,386 Members | 1,715 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,386 software developers and data experts.

can't understand how to do this with generics

Hi, if I have a generic class such as:
public class MyGroup<T> : Collection<MyChildClass>

and from one of it's methods I want to pass a reference to myself to the
following method in another class:

public void OnValidateChanged(MyGroup<MyChildClass> group)

I am trying:

_myReferenceToTheOtherClass.OnValidateChanged(this );

the error message is:

Error 2 Argument '1': cannot convert from 'MyNamespace.MyGroup<T>' to
'MyNamespace.MyGroup<'MyNamespace.MyChildClass>

I have tried all the possibilities I can think of, but can't crack it. I
guess I don't fully understand this <T> stuff.

thanks

Barry Mossman
Jun 8 '06 #1
19 1508
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
eT**************@TK2MSFTNGP02.phx.gbl...

| Hi, if I have a generic class such as:
| public class MyGroup<T> : Collection<MyChildClass>
|
| and from one of it's methods I want to pass a reference to myself to the
| following method in another class:
|
| public void OnValidateChanged(MyGroup<MyChildClass> group)
|
| I am trying:
|
| _myReferenceToTheOtherClass.OnValidateChanged(this );
|
| the error message is:
|
| Error 2 Argument '1': cannot convert from 'MyNamespace.MyGroup<T>' to
| 'MyNamespace.MyGroup<'MyNamespace.MyChildClass>
|
| I have tried all the possibilities I can think of, but can't crack it. I
| guess I don't fully understand this <T> stuff.

The <T> in MyGroup is expecting to be bound to a particular type. Unless you
bind it to MyChildClass, you cannot pass "this" as MyGroup<MyChaildClass>
unless you constrain the T to MyChildClass.

public class MyGroup<T> : Collection<MyChildClass> where T : MyChildClass

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #2
Joanna Carter [TeamB] ha scritto:
public class MyGroup<T> : Collection<MyChildClass> where T : MyChildClass


I'm quite "new" in C# (and in generics) but...
....where's the difference from:

public class MyGroup<MyChildClass> : Collection<MyChildClass>

Thanks,
Giulio - Italia
Jun 8 '06 #3
"Joanna Carter [TeamB]" <jo****@not.for.spam> wrote in message
news:Om**************@TK2MSFTNGP02.phx.gbl...
The <T> in MyGroup is expecting to be bound to a particular type. Unless
you
bind it to MyChildClass, you cannot pass "this" as MyGroup<MyChaildClass>
unless you constrain the T to MyChildClass.

public class MyGroup<T> : Collection<MyChildClass> where T : MyChildClass
Joanna Carter [TeamB]
Consultant Software Engineer


Thanks Joanna, it is good to see TeamB operating over here as well <g>

I added the where constraint, but still get the error message from the
following line for example:
MyGroup<MyChildClass> xxx = this;

Argument '1': cannot implicitly convert type 'MyNamespace.MyGroup<T>' to
'MyNamespace.MyGroup<'MyNamespace.MyChildClass>

Have you any further insight?

thanks

Barry Mossman

Jun 8 '06 #4
"Giulio Petrucci" <gi*************@RIMUOVIspeechvillage.com> a écrit dans le
message de news: Oc**************@TK2MSFTNGP05.phx.gbl...

| I'm quite "new" in C# (and in generics) but...
| ...where's the difference from:
|
| public class MyGroup<MyChildClass> : Collection<MyChildClass>

This is simply replacing the parameter T with another parameter called
MyChildClass.

However this particular MyChildClass is not a reference to your actual
MyChildClass, you might as well as use something like <childT>.

Adding a constraint at the end of the declaration means that, when you bind
your generic type to a particular type, it must, at least, derive from the
type mentioned in the constraint.

So...

public class MyGroup<T> : Collection<MyChildClass> where T : MyChildClass

....means :

You are creating a class that derives from, or "is a" Collection of
MyChildClass.

: Collection<MyChildClass>

You want users of this class to choose which class to which to bind MyGroup.

MyGroup<T>

When you bind to a class to MyGroup<>, it must derive from MyChildClass

where T : MyChildClass

However, if you always want MyGroup to be a collection of MyChildClass, then
you should consider revising whether and where you use generics. Generics
are meant to allow multiple different types to be handled in an identical
manner.

I get a feeling that you really don't need inheritance but composition
instead.

So you would have :

public class MyChildClass
{
...
}

public class MyGroup
{
public List<MyChildClass> items
{
...
}
}

Is that what you are after ?

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #5
Hi Joanna and thaks for your reply,
Hi everybody

Joanna Carter [TeamB] ha scritto:
[cut on all]
Is that what you are after ?


Actually no! :-)
I was only curious... but I didn't get that the constraint allow user to
use also objects of deriver classes! I found your explaination very...
"enlighing"!

Thanks again.
Best regards,
Giulio - Italia


Jun 8 '06 #6
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
%2****************@TK2MSFTNGP04.phx.gbl...

| Thanks Joanna, it is good to see TeamB operating over here as well <g>

For the record, I am not operating as TeamB here, just letting folks know
that there is someone who knows how to move between Delphi and C# :-)

| I added the where constraint, but still get the error message from the
| following line for example:
| MyGroup<MyChildClass> xxx = this;
|
| Argument '1': cannot implicitly convert type 'MyNamespace.MyGroup<T>' to
| 'MyNamespace.MyGroup<'MyNamespace.MyChildClass>
|
| Have you any further insight?

Does my reply to Giulio help at all ?

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #7
"Joanna Carter [TeamB]" <jo****@not.for.spam> wrote in message
news:eC**************@TK2MSFTNGP03.phx.gbl...
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
%2****************@TK2MSFTNGP04.phx.gbl...

Does my reply to Giulio help at all ?


<<<However, if you always want MyGroup to be a collection of MyChildClass,
then
you should consider revising whether and where you use generics. Generics
are meant to allow multiple different types to be handled in an identical
manner.>>>

My motivation was to have a type safe collection. There will only be one of
type of child in the collection.

I still haven't found a way to pass my generic class's this as per my
original question. In the meantime I am building a parameter array to pass
across the information that I need. I am still curious about how a generic
class is able to pass a reference of itself.

thanks anyway
Barry Mossman

Jun 8 '06 #8
Could be covariance? Try using:

public void OnValidateChanged<TGroupType >(MyGroup<TGroupType> group) where
TGroupType : MyChildClass

Marc
Jun 8 '06 #9
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
en**************@TK2MSFTNGP04.phx.gbl...

| My motivation was to have a type safe collection. There will only be one
of
| type of child in the collection.

Well, in that case, all you really need is to use List<T>. This is then
typesafe to whatever type you bind it.

e.g.

{
List<MyClass> myList = new List<MyClass>;

...
}

This provides a typesafe list that can only accept/return items of MyClass
or its derivatives as MyClass instances.

Now if you want to add extra functionality to the basic List<> class then
you can either create a wrapper class that holds a List<> or derive from it,
stating the type to which you want to bind it.

public class Group : List<MyClass>
{
...
}

Now you can do this :

{
Group g = new Group();

MyClass x = new MyClass();

g.Add(x); // typesafe

MyClass y = g[0]; //typesafe

...
}

However, if you don't want to add more functionality to the list class, this
is really redundant and you might as well declare a List<MyClass> whenever
you need one.

| I still haven't found a way to pass my generic class's this as per my
| original question. In the meantime I am building a parameter array to pass
| across the information that I need. I am still curious about how a generic
| class is able to pass a reference of itself.

If you want to pass such a list to another method, then all you have to do
is to declare a parameter of the List<MyClass> type.

public void OnValidateChanged(List<MyClass> group)
{
..
}

....or if you derive a Group class ...

public void OnValidateChanged(Group group)
{
..
}

Any better ?

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #10
"Marc Gravell" <ma**********@gmail.com> wrote in message
news:%2******************@TK2MSFTNGP04.phx.gbl...
Could be covariance? Try using:

public void OnValidateChanged<TGroupType >(MyGroup<TGroupType> group)
where TGroupType : MyChildClass


Thanks Marc, I couldn't get that to go either. It had the same error.

However this compiles, and works!
_myReferenceToTheOtherClass.OnValidateChanged(MyGr oup<MyChildClass>
)(object)(this);

It is ugly as, but it works. Do you think that this is the way to go?

thanks
Barry Mossman

Jun 8 '06 #11
"Joanna Carter [TeamB]" <jo****@not.for.spam> wrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
en**************@TK2MSFTNGP04.phx.gbl... Any better ?


Thanks Joanna. I have got an ugly (?) solution as per my posting that
crossed with yours.

I am going to take a break now, but will look further into what you have
said when I get back.

I really appreciate your assistance.

Barry Mossman
Jun 8 '06 #12
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
uK**************@TK2MSFTNGP02.phx.gbl...

| However this compiles, and works!
| _myReferenceToTheOtherClass.OnValidateChanged(MyGr oup<MyChildClass>
| )(object)(this);
|
| It is ugly as, but it works. Do you think that this is the way to go?

I "think" you are over-complicating things; trying to "overuse" generics
where it may not be necessary; been there, knitted the T-shirt. :-)

See my other reply to yourself.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #13
You're right... I think the problem here is that the problem code isn't all
visible and in one place;
Barry - if you are still reading, and this still isn't working, any chance
of a re-cap? i.e. what I have (from your posts) is:

public class MyChildClass { }
public class MyGroup<T> : Collection<MyChildClass> {
public void TestMethod() {
IncomingClass.OnValidateChanged(this);
}
}
public static class IncomingClass {
public static void OnValidateChanged(MyGroup<MyChildClass> group) {}
}
--
So: what role is T meant to be playing in this? Is it just a typo? If you
take out the <T> and <MyChildClass> then it works; if you change to the
following it works (this is if you want to support MyChildClass and anything
inherited from MyChildClass) - so: what is the intent here?

public class MyChildClass { }
public class MyGroup<T> : Collection<T> where T : MyChildClass {
public void TestMethod() {
IncomingClass.OnValidateChanged(this);
}
}
public static class IncomingClass {
public static void OnValidateChanged<T>(MyGroup<T> group) where T :
MyChildClass { }
}

Marc
Jun 8 '06 #14
"Marc Gravell" <ma**********@gmail.com> wrote in message
news:%2***************@TK2MSFTNGP05.phx.gbl...
So: what role is T meant to be playing in this? Is it just a typo? If you
take out the <T> and <MyChildClass> then it works; if you change to the
following it works (this is if you want to support MyChildClass and
anything inherited from MyChildClass) - so: what is the intent here?


also Joanna: <<<I "think" you are over-complicating things; trying to
"overuse" generics
where it may not be necessary; been there, knitted the T-shirt. :-)


It is clear to me now, thanks. I am still getting to grips with how, and
when, to use collections. I had built a collection class by descending from
Collection<T>. I am happy with this. The mistake I made was in thinking I
had to define my class as:
public class MyGroup<T> : Collection<MyChildClass>

rather than just:
public class MyGroup : Collection<MyChildClass>

Everything is working well now, and looks much cleaner. Thanks. Sorry for
wasting your time.

To use Marc's code I have:

public class MyChildClass { }
public class MyGroup : Collection<MyChildClass> {
public void TestMethod() {
IncomingClass.OnValidateChanged(this);
}
}
public static class IncomingClass {
public static void OnValidateChanged(MyGroup group) {}
}

regards
Barry Mossman



Jun 8 '06 #15
I don't think anybody's time has been wasted, and I'm glad your problem is
resolved.

Marc
Jun 8 '06 #16
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
%2****************@TK2MSFTNGP04.phx.gbl...

| It is clear to me now, thanks. I am still getting to grips with how, and
| when, to use collections. I had built a collection class by descending
from
| Collection<T>. I am happy with this.

Just to check, did you really want to derive from Collection<T> and was it
in order to override/add to the default behaviour ?

| Everything is working well now, and looks much cleaner. Thanks. Sorry for
| wasting your time.

If you were wasting out time, we would have ignored you :-))

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #17
"Joanna Carter [TeamB]" <jo****@not.for.spam> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...>
Just to check, did you really want to derive from Collection<T> and was it
in order to override/add to the default behaviour ?


No overriding, but lots of additional members. I wanted a type safe
collection, and using Collection<T> as a base seemed to give me at least
some some functionality for free. There isn't any point to the non-generic
collection classes any more is there?

regards
Barry Mossman
Jun 8 '06 #18
"Barry Mossman" <NO****@NoSpam.com> a écrit dans le message de news:
%2****************@TK2MSFTNGP03.phx.gbl...

| No overriding, but lots of additional members. I wanted a type safe
| collection, and using Collection<T> as a base seemed to give me at least
| some some functionality for free. There isn't any point to the non-generic
| collection classes any more is there?

Hmmm, if you'll pardon the expression, this starts to have a "funny smell"
about it.

Are all the other members related to the management of the Group ? and do
they all fit with the concept of a Group being a collection ?

Clues like does the Group have a "header", a bit like an Invoice and its
lines ?

I am only asking these questions to prompt you to think whether you should
be deriving from or containing the list. :-)

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jun 8 '06 #19
Indeed - don't use ArrayList; I think Joanna was saying that you can use
List<T>, Collection<T> etc directly if all you need is a container; but if
you are adding methods then inheritance or encapsulation are the way to go.
The former is easier, the latter is cleaner (as it abstracts the specific
implementation), but you need to do more plumbing. What you have should be
just fine.

Marc

Jun 8 '06 #20

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

Similar topics

2
by: SAN CAZIANO | last post by:
can you help me please because I can't understand why the code doesn't seems to function very well: in onkeypress it must verify if insert number or string value in the fiels, but it doesn't...
6
by: hoox2 | last post by:
void push_front(Node const*& head, int data); Can someone tell me what it means for "const*&"? A reference or a pointer?
10
by: forgotten field | last post by:
Hi,how are you? I have been studying C++ by myself, but recently I am having a real problem. I am learning about the basic usage of a doubly linked list using polymorphism. However, I have got the...
1
by: charles | last post by:
when i read the notable book of inside the c++ bject model ,i was confused by the chapter 3.3. i was confused by the statement as follow: chaper 3.3: Given the following pair of program...
2
by: DC | last post by:
Hi, I need to asynchronously read from a network (TCP) stream, and I am having trouble with retrieving whole blocks; I get a break in the data block every 1460 bytes which relates to network...
2
by: RC | last post by:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sort2 You can see above link or read below i copy/paste from above link <script type="text/javascript"> function sortNumber(a, b)...
5
by: Frederick Dean | last post by:
Hi,guys! I'm reading Stephen Dewhurst's book "C++ Gotchas"£¬in gothca #7, I meet a weird case: bool Postorder::next() { switch (pc) case START: while (true) if (!child()) { pc = LEAF; return...
4
by: saunakinju | last post by:
I can't Understand that if i add menu in my VB.Net Application with the use of Javascript,thn how can i open a perticular form on click of submenu item of that menu.Because menu will be appear when i...
6
by: CD1 | last post by:
#include <string> This code won't compile. There is no variable called "foo2". :)
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
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,...
0
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...
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...

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.