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

Generic method: cannot convert 'T' to ...

class A {}

class B {}

interface MyInterface
{
void method(A a);
void method(B b);
}

class Foo
{
public Foo(MyInterface myInterface)
{
_myInterface = myInterface;
}

private bool Process<T>(T t)
{
if (t == null) return false;
_myInterface.method(t);

// The previous line generates 2 errors
// Error 1: The best overload method match for 'MyInterface.method(A)'
// has some invalid argument
// Error 2: cannot convert from 'T' to 'A'

return true;
}

// I would like to avoid to implement the core of Process
// for each type as follows:
// private bool Process(A a)
// {
// if (a == null) return false;
// _myInterface.method(a);
// return true;
// }
// private bool Process(B b)
// {
// if (b == null) return false;
// _myInterface.method(a);
// return true;
// }

public void Process(object o)
{
if (Process(o as A)) return;
if (Process(o as B)) return;
throw new Exception();
}

private MyInterface _myInterface;
}

I would like to avoid to implement Process for each type. How can I do
this in C# ?

Thanx.

Jun 26 '06 #1
2 15690
Christophe,

It is not possible to pull this off with generics.

The reason why you get this error message is that the compiler doesn't know
at the time of compilation what the real type of the object is.
In your case because it doesn't know the type of the object the compiler
cannot verify that the parameter can be converted to A type in order to call
the method. This can be overcome using constraints.
Unfortunately there might be only one type constriant, but we need to have
two in our case. You can rework the sample a little bit by marking the
classes with marker interfaces. The reason for doing this is because we may
have more than one interface constraint

interface IA{}
class A:IA { }

interface IB{}
class B:IB { }

interface MyInterface
{
void method(IA a);
void method(IB b);
}

class Foo
{
MyInterface _myInterface;
public Foo(MyInterface myInterface)
{
_myInterface = myInterface;
}

private bool Process<T>(T t) where T:IA,IB
{
if (t == null) return false;
_myInterface.method(t);

// The previous line generates 2 errors
// Error 1: The best overload method match for 'MyInterface.method(A)'
// has some invalid argument
// Error 2: cannot convert from 'T' to 'A'

return true;
}
}
Now if you try to compile this code you'll get antoher error, which I
believe is more easier to understand:
Error 2 The call is ambiguous between the following methods or properties:
'ConsoleApplication1.Program.MyInterface.method(Co nsoleApplication1.Program.IA)'
and
'ConsoleApplication1.Program.MyInterface.method(Co nsoleApplication1.Program.IB)'
D:\Projects\Delme2005\WindowsApplication1\ConsoleA pplication1\Program.cs 50
5 ConsoleApplication1

And this is why you scenario cannot be implemented. The compiler doesn't
know the real type of the paramter, but it knows that it implements certain
interfaces, now when it comes to calling the methods it cannot decide which
one to call, both are possible. This sample by the way is not correct again
because neither B nor A implemets both interfaces, but it demonstrates what
error you'll eventually get.

Once again:
1. Without using constraints the effective base class for *t* is Object and
there is no conversion from Object to neither A or B.
2. There is no constraints that could help you in this case.
3. Even if there were such constraints the compiler eventually will stumble
with choosing the correct method overload to call.
These are my two cents. I hope other guys in the group will throw their
opinions on the problem.
--
HTH
Stoitcho Goutsev (100)
"Christophe" <ch******@swing.be> wrote in message
news:11**********************@y41g2000cwy.googlegr oups.com...
class A {}

class B {}

interface MyInterface
{
void method(A a);
void method(B b);
}

class Foo
{
public Foo(MyInterface myInterface)
{
_myInterface = myInterface;
}

private bool Process<T>(T t)
{
if (t == null) return false;
_myInterface.method(t);

// The previous line generates 2 errors
// Error 1: The best overload method match for 'MyInterface.method(A)'
// has some invalid argument
// Error 2: cannot convert from 'T' to 'A'

return true;
}

// I would like to avoid to implement the core of Process
// for each type as follows:
// private bool Process(A a)
// {
// if (a == null) return false;
// _myInterface.method(a);
// return true;
// }
// private bool Process(B b)
// {
// if (b == null) return false;
// _myInterface.method(a);
// return true;
// }

public void Process(object o)
{
if (Process(o as A)) return;
if (Process(o as B)) return;
throw new Exception();
}

private MyInterface _myInterface;
}

I would like to avoid to implement Process for each type. How can I do
this in C# ?

Thanx.

Jun 26 '06 #2
Thanx a lot. Good contribution :-)

Christophe

Jun 27 '06 #3

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

Similar topics

49
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another...
17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
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...
3
by: Otis Mukinfus | last post by:
I've been wrestling with this for a while and can't figure it out. I have a generic method with the following signature: //this compiles OK public abstract class DataMethod { public...
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...
4
by: sklett | last post by:
I'm revisiting an old series of overloaded methods I have and I would like to convert them to a single generic method. Here is the method in it's current, overloaded implementation: <code>...
3
by: BombDrop | last post by:
Can any one help I have a method that will return a List to be bound as a datasource to a combobox see code for population below. I get the following error when i try to compile Error 29 ...
10
by: phancey | last post by:
I'm quite new to generics. I have 2 generic classes: MyClass<Tand MyOtherClass<T>. MyClass<Thas 2 public Add methods Add(MyOtherClass<T>); Add(MyOtherClass<Wrapper<T>>); (Wrapper<Tis another...
4
by: Tony | last post by:
Hello! Below I have a complete working program.with some simple classes one of these is a generic class. The question is about this method GetCows() {...} which is a member in the generic...
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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
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...
0
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...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.