Interface definition: How can a method return an 'abstract' object?

F

Francesc Benavent

Hi all, I'm trying to implement an interface, shared for different
classes, with a method that must return an object belonging to the
same class that implements the interface.

May be an example should be clearer:

==============================
public interface IVector
{
[***] Addition([***]);
}

public class BinaryVector : IVector
{
BinaryVector Addition (BinaryVector)
{
}
}

public class RealVector : IVector
{
RealVector Addition (RealVector)
{
}
}

==============================

That is:

1) Define IVector.

2) if BinaryVector implements the IVector interface, it MUST have a
method that receives a BinaryVector and returns a BinaryVector.

3) if RealVector implements the IVector interface, it MUST have a
method that receives a RealVector and returns a RealVector.

QUESTION: How I must define this interface at [***]?

Please, any suggestions or correction would be welcomed,

Francesc


Note: At first I tried to define an abstract class Vector from others
inherited, but I thought that an Interface would be better.
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi,

I'd rather use operator overloading for vectors. Interfaces are not that
good for unary/binary operations that are type-bound. You would otherwise
have to declare several overloads of, say, Addition, and check whether the
arguments passed are of valid types within the method implementation. This
prevents compile-time type safety and is not therefore a good idea.
 
M

Mattias Sjögren

Francesc,
QUESTION: How I must define this interface at [***]?

In current versions I believe the best you can do is to declare the
method as

IVector Addition(IVector vector);

And in the implementing classes you do

public class BinaryVector : IVector
{
public BinaryVector Addition (BinaryVector vector)
{
}

IVector IVector.Addition (IVector vector)
{
return Addition( (BinaryVector)vector );
}

}


In v2.0 with generics support you'll be able to get the behavior you
want.



Mattias
 
F

Francesc Benavent

Hi Dimitriy,
I'd rather use operator overloading for vectors. Interfaces are not that
good for unary/binary operations that are type-bound. You would otherwise

Thanks for your suggestions, indeed it seems a good idea to overload
operators to work with vectors, and it simplifies very much the naming
of methods to work between vectors and between vectors and numeric
constants.

I had another problem, after define the Vector classes I need to
create a clustering algorithm able to work with any vector that
implemented IVector, and I belive that Mattias's messages have gime
some clues (Mattias, I'll answer to you after try it).

thanks very much,

Francesc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top