views:

102

answers:

2

Hello SOers,

imagine you have the following interfaces:

public interface IInterfaceA : IInterfaceX
{
    //
    // declarations
    //
}

public interface IInterfaceB : IInterfaceX
{
    //
    // declarations
    //
}

public interface IInterfaceC : IInterfaceX
{
    //
    // declarations
    //
}

Now I want to replace the following three methods which perform almost the same with a single function:

class SomeClass
{
    IInterfaceA myVarA;
    IInterfaceB myVarB;
    IInterfaceC myVarC;

    void SomeMethodA(IInterfaceX someVarX)
    {
        myVarA = (IInterfaceA)someVarX;
    }

    void SomeMethodB(IInterfaceX someVarX)
    {
        myVarB = (IInterfaceB)someVarX;
    }

    void SomeMethodC(IInterfaceX someVarX)
    {
        myVarC = (IInterfaceC)someVarX;
    }
}

I thought about something like:

void SomeMethod(IInterfaceX targetVar, IInterfaceX someVarX)
{
    //
    // here's my problem
    //
    targetVar = (CastIDontKnowHowToPerform)someVarX;
}

which is used sth. like

SomeMethod(myVarA, someVarX);        
SomeMethod(myVarB, someVarX);        
SomeMethod(myVarC, someVarX);

So my questions are:

  • Is it possible what I want to get?

  • How to perform this cast I don't know how to perform?

  • Perhaps a design pattern is more appropriate

I'm just looking for the best way to refactor those three functions by replacing them by a single one.

Things I've tried so far: I used things like object.GetType() and object.GetType().GetInterfaces() which works well to get the type of an object or its interface(s) but none to set the type of an object to its interface.

Hope you can help me...

Regards,

Inno

[EDIT] Ah, damn it... after clicking "Ask your question" and having a short look at it this seems to a be typical case for a generic function (or a template in C++-term). [/EDIT]

+9  A: 
void SomeMethod<T>(out T targetVar, IInterfaceX someVarX) where T: IInterfaceX
{
       targetVar = (T) someVarX;
}
James Curran
Yeah, this is definitely the best way to do it.
Noldorin
Do you need the 'out' keyword ?
Julien Poulin
Yes, you need "out", since we are changing the value of targetVal, rather than merely modifying what targetVal references.
James Curran
+2  A: 

One possibility is the "is" operator:

void SomeMethod(IInterfaceX someVarX)
{
    if (someVarX is IInterfaceA)
        SomeMethodA((IInterfaceA)someVarX);
    else if (...
}

A better method would be to put the operation into the IInterfaceX to avoid casting altogether:

void SomeMethod(IInterfaceX someVarX)
{
    someVarX.SomeMethod();
}
David Schmitt