Re: alternatives to unboxing..




"gökhan" <g.h.bakir@xxxxxxxxx> wrote...

I fear this question might be too basic, however being
a c++ veteran I have trouble to get a good desing in c# running.

I fear you have left out some crucial information in your example, which can
make it harder to interpret your problem, however...

As I understand, you forgot to include that "A" also is a subclass of some
other class which you are not in position to modify? Am I right?

class A : SomeExternalClassWithVirtualFunMethod
{
public void vectorfun(Vector a,Vector b){}

public override void fun(object a,object b)
{
vectorfun( (Vector) a , (Vector) b);
}
}

The solution above seems to be the most straightforward.

I would like to call the "fun" member of an instance of A
using Vector instances and VectorChild instances.

As VectorChild and VectorChildChild both are subclasses to your Vector,
there's no need to do any other casting than to your Vector.

What is the right thing to do?

If you want to make it "safer" in order to avoid InvalidCastExceptions if a
or b *not* is one of your Vector's subclasses, you can use "as", e.g.:

public override void fun(object a,object b)
{
Vector va = a as Vector;
Vector vb = b as Vector;

if (va != null && vb != null)
{
vectorfun(va , vb);
}
}

http://msdn2.microsoft.com/en-us/library/cscsdfbt(VS.80).aspx

Unfortunately I have to stick with the object type since my
objects (of arbitrary type) are stored in a HashTable.

If they weren't of an "arbitrary type", you could exchange the HashTable
with e.g. a "generic" Dictionary<KeyType, Vector>.


// Bjorn A


.



Relevant Pages

  • Re: alternatives to unboxing..
    ... you forgot to include that "A" also is a subclass of some ... public override void fun ... using Vector instances and VectorChild instances. ... The code above would lead to an casting exception if the objects are of ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: alternatives to unboxing..
    ... Then fun() becomes just: ... public override void fun{ ... using Vector instances and VectorChild instances. ... In C++ the compiler is able to automatically cast down... ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: alternatives to unboxing..
    ... public override void fun ... using Vector instances and VectorChild instances. ... As VectorChild and VectorChildChild both are subclasses to your Vector, ... The code above would lead to an casting exception if the objects are of ...
    (microsoft.public.dotnet.languages.csharp)
  • alternatives to unboxing..
    ... have trouble to get a good desing in c# running. ... // a base class ... public override void fun{ ... using Vector instances and VectorChild instances. ...
    (microsoft.public.dotnet.languages.csharp)