So, previously I did that
if (instance is typeA)
return (instance as typeA).CustomProperty;
if (instance is TypeB)
return (instance as TypeB).CustomProperty;
if (instance is TypeC)
return (instance as TypeC).CustomProperty;


But with newer c#, we can use the as operator to check and cast. if the cast is invalid, the resulting variable will be null and the is can be checked into an if. So I can do this instead.
if (instance is TypeA cast)
return cast.CustomProperty;
if (instance is TypeB cast2)
return cast2.CustomProperty;
if (instance is TypeC cast3)
return cast3.CustomProperty;
However, do note that i must give a different cast name each time I use it. I guess those variables are declared in the scope of the function (and not the if… which is obvious if you think about it.
Thought it’s kinda weird looking.
Does someone has a better way to do this ? Best way would be to change the class yeah sure, but it will probably not change. So any other way to represent this ? there is 10 similar iffffss next to each other.
You should probably set the base type these classes derive from to have the CustomProperty property, then you override what that returns in each derived type. It would make your design significantly easier.
If it’s just a general question you can use the new pattern-matching switch expression, but you can’t escape the variables.
Your items:


Wouldn’t it just be more readable to name the casted variable after the type?
This, if you care about the specific type it only makes sense to give it a name that represents what it is specifically rather than a generic name.
Your example doesn’t really tell me what you’re doing to with your variable named instance, or the classes TypeA, TypeB, or TypeC. So I don’t know what CustomProperty is or how it is used by the containing classes.
That’s a kind of silly example and you can do some similar things with a non-abstract base class, but you get the idea.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/

FYI: https://www.reddit.com/wiki/markdown#wiki_code_blocks_and_inline_code
usually it indicates a bad design in a first place. If you have code like this, all types TypeA, TypeB, TypeC probably should have been inherited from the same base type that has a property CustomProperty or at least implement same interface that has same property CustomPropery.

But if you can not fix that, then you will be stuck with this “weird” code. Not much you can do.
C# devs
null reference exceptions

source