What is the difference between is and as operators in C#?
What is the difference between is and as operators in C#?
The is and as operators in C# are used for type checking and casting, but they have some key differences:
The is operator checks if an object is compatible with a given type. It returns true if the object is compatible, and false otherwise. For example:
object obj = "hello";
bool isString = obj is string; // isString = true
bool isInt = obj is int; // isInt = false
In contrast, the as operator attempts to cast an object to a given type. If the cast is successful, it returns the object as the target type. If the cast fails, it returns null. For example:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.