DisplayMyName
DisplayMyName

Reputation: 320

How to access class methods after institiating object as interface?

What I would like to do is to have an interface like IResult result = new SomeResult(), and then depending on some if's, access some specific fields after casting.

if (a == b) 
{
   result = (SomeOtherResult) result;
   result.fieldFromSomeOtherResult = 42;
}

Obviously now I can't do that, because result's interface doesn't have this field, neither does SomeResult class, only SomeOtherResult class. How should I solve this?

Upvotes: 0

Views: 50

Answers (1)

Dai
Dai

Reputation: 155065

If you're using C# 7.0 or later, use the is operator:

IResult result = new SomeResult();

if( a == b )
{
    if( result is SomeResult someResult )
    {
        someResult.fieldFromSomeOtherResult = 42;
    }
    else if( result is SomeOtherResult someOtherResult )
    {
        someOtherResult.x = 123;
    }
} 

That said, if you're initializing IResult result using an explicit new SomeResult() then you should declare result with the SomeResult type.

Upvotes: 4

Related Questions