Shafeeq Abrar
Difference between is and As operators in C#
By Shafeeq Abrar in C# on Apr 24 2024
  • Babita
    May, 2024 10

    is checks if an object is compatible with a given type and returns a boolean result. as attempts to cast an object to a specified type and returns null if the cast fails.

    • 1
  • Jayraj Chhaya
    Apr, 2024 30

    In C#, the is operator is used for type testing, returning a boolean value indicating whether an object is compatible with a given type. For example:

    1. if (obj is MyClass)
    2. {
    3. // Do something
    4. }

    On the other hand, the As operator is used for casting objects to a specified type if the conversion is valid. It returns null if the conversion is not possible. Here’s an example:

    1. MyClass myObj = obj as MyClass;
    2. if (myObj != null)
    3. {
    4. // Conversion successful
    5. }

    In essence, is checks compatibility, while As performs a safe cast and returns null if the cast fails.

    • 0
  • Aman Agarwal
    Apr, 2024 29

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS