What is the difference betwe...
What is the difference betwe...
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[1][3]. 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
[1][4]. For example:
object obj = "hello";
string str = obj as string; // str = "hello"
int? i = obj as int; // i = null
Some other key differences:
is
can be used for reference, boxing, and unboxing conversions, while as
is limited to nullable, reference, and bo...senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào