0

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?

4
  • 1
    How does IResult, SomeResult and SomeOtherResult related to each other? Commented May 5, 2020 at 10:50
  • SomeResult and SomeOtherResult implements IResult. Commented May 5, 2020 at 10:52
  • Being more specific (why IResult, what field, what are you trying, etc.) will help to get specific to your case answers. There could be an existing pattern already. Maybe use generics to pass SomeOtherResult type or perhaps it shouldn't be IResult, but a more suitable interface (implemented by SomeOtherResult). Commented May 5, 2020 at 11:17
  • I think I approached it from a bit incorrect point of view. @Dai's answer helped me realise something, so I've checkmarked it. Commented May 5, 2020 at 11:19

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To be precise, is operator for type checking was exist before C# 7, C# 7 introduced a pattern matching with is operator
@PavelAnikhouski I don't like how the C# <del>marketing material</del> documentation refers to it as "pattern matching" because it makes me think of Haskell matching or otherwise implies (to me, at least) that it's an O(1) operation regardless of the size of the match's candidate expression list - when in reality it's an O(n) ordered sequence of type-checks - and that's all it is. I don't think it's possible for a language to have true pattern-matching without structural typing and value-typing (i.e. each distinct value, or set of values constitutes its own separate type) which C# lacks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.