Laurence
Laurence

Reputation: 1020

Need generic method to return type T unless T implements interface I, in which case return I

I have a generic method which returns a type T. Now I want to modify it so that if T happens to implement interface I, an additional property is set on the object (i.e. from I).

Something like this (but of course this does not work):

    public T MyMethod<T>()
    {
        T resultAsT = some function ....

        var resultAsI = (resultAsT as I);

        if (resultAsI != null)
        {
            resultAsI.PropertyOnlyAvailableInI = 99;
            return resultAsI;
        }
        else
            return resultAsT;
    }

Is something like this possible?

Upvotes: 0

Views: 179

Answers (2)

user1618077
user1618077

Reputation: 9

If you really want to make it work then you can do so:

 public object MyMethod()
     {
         object resultAsT = something;

    var resultAsI = (resultAsT as ISomething);

    if (resultAsI != null)
    {
        resultAsI.PropertyOnlyAvailableInI = 99;
        return resultAsI;
    }
    else
        return resultAsT;
}

But it seems to me that you want to do factory that implements the strategy pattern. Where the object is created with the use of strategy pattern is executed to initialize certain properties of the object.

Upvotes: -1

Dmitry
Dmitry

Reputation: 14059

This should work:

public T MyMethod<T>()
{
    T resultAsT = some function ....

    var resultAsI = (resultAsT as I);

    if (resultAsI != null)
    {
        resultAsI.PropertyOnlyAvailableInI = 99;
    }
    return resultAsT;
}

The method cannot return anything except T, so you should always return resultAsT.

Upvotes: 7

Related Questions