+ 3

What is difference between "is" and "as" operators in c#?

23rd Feb 2020, 2:49 PM
Shashank Mishra
Shashank Mishra - avatar
2 Réponses
+ 3
The difference between the two operators in C# is that "is" checks if a object can be converted to a specific type, and returns true if possible; "as", on the other hand, actually attempts to convert an object to a specific type and returns null if it fails.
23rd Feb 2020, 3:32 PM
Jianmin Chen
Jianmin Chen - avatar
+ 2
Let's take a look at a example of "is": public class X { int value = 5; } Now, let's say we create a instance of X in main: X object_x = new X(); If we use is to check if object_x is a X object: Console.WriteLine(object_x is X); This will print true to the console as object_x is derived from our class X. Now let's look at "as" along with the same class X, and the same object object_x. Let's try to convert our object to a string: string string_x = object_x as string; "as" will attempt to convert object_x to a string. If not possible, it will string_x will be equal to null. Luckily, we can convert a object to a string, so it won't be equal to null.
23rd Feb 2020, 3:41 PM
Jianmin Chen
Jianmin Chen - avatar