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

Generics and conversion

Hi,

I have classes A1 and A2 which implement the interface IA.
Now I need a method m that works on Lists of objects of either class.
So I wrote something like

void m(List<IA> myList)
{
// do something with myList
}

and wanted to call it like this

main()
{
List<A1> list = new List<A1>();
// fill list
m(list); // <===
// more code
}

Then the compiler complains about the call m(list); with the error
CS1503: cannot convert from 'System.Collections.Generic.List<A1>'
to 'System.Collections.Generic.List<IA>'.

I can use ArrayLists instead of the List<>'s and the problem goes away,
but I have not found a solution using generic collections.
Any suggestions?

TIA

Ralf
Feb 1 '06 #1
8 1545
Hello, Ralf!

RP> I have classes A1 and A2 which implement the interface IA.
RP> Now I need a method m that works on Lists of objects of either class.
RP> So I wrote something like

RP> void m(List<IA> myList)
RP> {
RP> // do something with myList
RP> }

RP> and wanted to call it like this

RP> main()
RP> {
RP> List<A1> list = new List<A1>();
RP> // fill list
RP> m(list); // <===
RP> // more code
RP> }

Use List<IA>list = new List<IA>();

following code will be still valid
list.Add(new A1());
list.Add(new A2());

m(list);

The reason why compiler generated an error is that you specified different types in List<> container in class declaration and in List<> variable declaration in method main(...)

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Feb 1 '06 #2
Ralf,

Instead of passing in List<IA> into your method, you should do this:

void m<T>(List<T> myList) where T : IA
{

}

This way, you can pass the type of T to the method (or in your case, you
can just pass the parameter and it will be inferred).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Ralf Propach" <ra**@heeg.de> wrote in message
news:dr**********@charly.heeg.de...
Hi,

I have classes A1 and A2 which implement the interface IA.
Now I need a method m that works on Lists of objects of either class.
So I wrote something like

void m(List<IA> myList)
{
// do something with myList
}

and wanted to call it like this

main()
{
List<A1> list = new List<A1>();
// fill list
m(list); // <===
// more code
}

Then the compiler complains about the call m(list); with the error
CS1503: cannot convert from 'System.Collections.Generic.List<A1>'
to 'System.Collections.Generic.List<IA>'.

I can use ArrayLists instead of the List<>'s and the problem goes away,
but I have not found a solution using generic collections.
Any suggestions?

TIA

Ralf

Feb 1 '06 #3
You should use 'where' :

static void MethodName<TItem>(List<TItem> list)
where TItem: IA
{
foreach (TItem item in list)
{
item.DoSome();
}
}

Feb 1 '06 #4
Just to ice the cake you could consider the more general:

void m<T>(IEnumerable<T> sequence) where T: IA
{
}

Unless you really need Count or indexing or can somehow figure out a usefukl
way to add stuff to the list without an input of type T.

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:e6**************@TK2MSFTNGP11.phx.gbl...
Ralf,

Instead of passing in List<IA> into your method, you should do this:

void m<T>(List<T> myList) where T : IA
{

}

This way, you can pass the type of T to the method (or in your case,
you can just pass the parameter and it will be inferred).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Ralf Propach" <ra**@heeg.de> wrote in message
news:dr**********@charly.heeg.de...
Hi,

I have classes A1 and A2 which implement the interface IA.
Now I need a method m that works on Lists of objects of either class.
So I wrote something like

void m(List<IA> myList)
{
// do something with myList
}

and wanted to call it like this

main()
{
List<A1> list = new List<A1>();
// fill list
m(list); // <===
// more code
}

Then the compiler complains about the call m(list); with the error
CS1503: cannot convert from 'System.Collections.Generic.List<A1>'
to 'System.Collections.Generic.List<IA>'.

I can use ArrayLists instead of the List<>'s and the problem goes away,
but I have not found a solution using generic collections.
Any suggestions?

TIA

Ralf


Feb 1 '06 #5
I would say that this is definitely questionable, since it decreases the
amount of functionality that the OP was looking for in his first post. The
only thing I might change would be co make List<T> IList<T> instead.

IEnumerable<T> only works if you are cycling through the list, and not
making changes of any sort to it.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:X1*********************@fe3.news.blueyonder.c o.uk...
Just to ice the cake you could consider the more general:

void m<T>(IEnumerable<T> sequence) where T: IA
{
}

Unless you really need Count or indexing or can somehow figure out a
usefukl way to add stuff to the list without an input of type T.

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:e6**************@TK2MSFTNGP11.phx.gbl...
Ralf,

Instead of passing in List<IA> into your method, you should do this:

void m<T>(List<T> myList) where T : IA
{

}

This way, you can pass the type of T to the method (or in your case,
you can just pass the parameter and it will be inferred).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Ralf Propach" <ra**@heeg.de> wrote in message
news:dr**********@charly.heeg.de...
Hi,

I have classes A1 and A2 which implement the interface IA.
Now I need a method m that works on Lists of objects of either class.
So I wrote something like

void m(List<IA> myList)
{
// do something with myList
}

and wanted to call it like this

main()
{
List<A1> list = new List<A1>();
// fill list
m(list); // <===
// more code
}

Then the compiler complains about the call m(list); with the error
CS1503: cannot convert from 'System.Collections.Generic.List<A1>'
to 'System.Collections.Generic.List<IA>'.

I can use ArrayLists instead of the List<>'s and the problem goes away,
but I have not found a solution using generic collections.
Any suggestions?

TIA

Ralf



Feb 1 '06 #6
If you reread my post you will see that I said:
Unless you really need Count or indexing or can somehow figure out a
usefukl way to add stuff to the list without an input of type T.

Also there was nothing in the original post that suggested that list
functionality rather than enumerable functionality was required.

Note:
1) It is impossible for m to Add to List<T> as T is not constrained to new()
and even if it was it is not likely that he needs to add default values to
the list.
2) I assume that m does not sort the list or compare T's in any way since it
is not constrained to IComparable
3) In fact T is not constrained to anything at all which means that very
little can be efficiently done on the list.

This makes it rather hard to imagine what the method might be that would
require list rather than enumerable functionality.

In my experience people are always requesting more of their parameters than
is actually required.

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:eY**************@tk2msftngp13.phx.gbl... I would say that this is definitely questionable, since it decreases
the amount of functionality that the OP was looking for in his first post.
The only thing I might change would be co make List<T> IList<T> instead.

IEnumerable<T> only works if you are cycling through the list, and not
making changes of any sort to it.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:X1*********************@fe3.news.blueyonder.c o.uk...
Just to ice the cake you could consider the more general:

void m<T>(IEnumerable<T> sequence) where T: IA
{
}

Unless you really need Count or indexing or can somehow figure out a
usefukl way to add stuff to the list without an input of type T.

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote
in message news:e6**************@TK2MSFTNGP11.phx.gbl...
Ralf,

Instead of passing in List<IA> into your method, you should do this:

void m<T>(List<T> myList) where T : IA
{

}

This way, you can pass the type of T to the method (or in your case,
you can just pass the parameter and it will be inferred).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Ralf Propach" <ra**@heeg.de> wrote in message
news:dr**********@charly.heeg.de...
Hi,

I have classes A1 and A2 which implement the interface IA.
Now I need a method m that works on Lists of objects of either class.
So I wrote something like

void m(List<IA> myList)
{
// do something with myList
}

and wanted to call it like this

main()
{
List<A1> list = new List<A1>();
// fill list
m(list); // <===
// more code
}

Then the compiler complains about the call m(list); with the error
CS1503: cannot convert from 'System.Collections.Generic.List<A1>'
to 'System.Collections.Generic.List<IA>'.

I can use ArrayLists instead of the List<>'s and the problem goes away,
but I have not found a solution using generic collections.
Any suggestions?

TIA

Ralf



Feb 2 '06 #7
Nicholas Paldino [.NET/C# MVP] wrote:
Ralf,

Instead of passing in List<IA> into your method, you should do this:

void m<T>(List<T> myList) where T : IA
{

}

This way, you can pass the type of T to the method (or in your case, you
can just pass the parameter and it will be inferred).

Hope this helps.


Yes, thanks, this "trick" with the where clause was exactly what I was looking for.

Ralf
Feb 2 '06 #8
"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:Cf********************@fe2.news.blueyonder.co .uk...
If you reread my post you will see that I said:
3) In fact T is not constrained to anything at all which means that very
little can be efficiently done on the list.
In the original message, T was constraint to (actually, was) the
interface IA, which could have any number of requirements that we do not
know about.
1) It is impossible for m to Add to List<T> as T is not constrained to new() and even if it was it is not likely that he needs to add default values to
the list.


Nor is there any requirement that items added to the list by m() be
default constructed:

void m<T>(List<T> myList) where T : IA
{
IA a = CreateANewA1orA2();
myList.Add(a);
}

class A1 : IA {}
class A2 : IA {}

IA CreateANewA1orA2()
{
if (DateTime.Now.Millisecond < 500)
return new A1();
else
return new A2();
}
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
Feb 3 '06 #9

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

Similar topics

4
by: Tom Jastrzebski | last post by:
Hello everybody, Here is the problem I came across experimenting with Generics. I would like to write a class or a struct adding integer to any other, initially undefined *numeric type*. So, my...
3
by: Tom Jastrzebski | last post by:
Hello everybody, Here is another problem with generics I come across. Let's say I want to implement a structure performing some operations on some numeric type. I can not than just return...
11
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes...
9
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal...
6
by: Andrew Ducker | last post by:
I have a class "Validator" which can be cast to a Control. The code: ValidTextBox t = (ValidTextBox)v; works just fine. However, because v doesn't descend from t, I can't use "is" or "as". I...
7
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
4
by: Random | last post by:
I want to define a generics method so the user can determine what type they expect returned from the method. By examining the generics argument, I would determine the operation that needs to be...
5
by: Fredo | last post by:
I'm new to Generics (years and years of VS.NET 2003 development, but very little .NET 2.0+). I have some routines for conversion from RGB to different color spaces and back. I would like the...
3
by: =?Utf-8?B?RnJhbmsgVXJheQ==?= | last post by:
Hi all I have some problems with Crystal Reports (Version 10.2, Runtime 2.0). In Section3 I have added a OLE Object (Bitmap). Now when I open the report in my code I would like to set this...
3
by: Anders Borum | last post by:
Hello, I've worked on an API for quite some time and have (on several occasions) tried to introduce generics at the core abstract level of business objects (especially a hierarchical node). The...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...

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.