I have been seeing many developers are casting between two types using is operator. As we know, we do have as operator also for type casting.
For purpose of this article, we are going to use below two classes,
Very first let us try to understand, how is operator works?
So , if we are running below code , we will get output as true because ofccouse p is a Player.
Now let us modify code a bit and check whether p is compatible to Math class or not? Since p is instance of class Player and Player class does not have Math class in hierarchy tree, so output we will get false.
If we compare an object against null, we will get always an output as false.
Normally we use is operator like below,
In above snippet, C# checks type compatibility twice and it costs the performance. So to simplify above code and improve performance C# gives us as operator to compare.
as operator find type compatibility, If an object is not compatible with given type then as operator returns null.
Leave a Reply