
Illustration of Operator Keywords (as, is) with Examples in C# (C Sharp) C# provides
eight Operator Keywords where in each of them are used to perform varied
activities. This article will introduce two operator keywords namely as
and is. These keywords are illustrated with simple examples in this article. Operator
Keyword as: This keyword
is used to perform type conversions between reference types that are compatible
with one another. Normally you do type conversions using casting. But
when you perform a type conversion that is not valid, an exception will
be thrown. Here is an example: class testClass{ In this example,
string2 is assigned to string1. Here casting is not required. Anyways
it is legal and it works fine. You have also attempted to cast object
of testClass as a string and assign it to string2. This is invalid and
hence you will end up in an exception. What if you have an alternate solution
to display null instead of throwing an exception? You can achieve it using
as keyword. Here is the modified code of sampleClass using as keyword: class sampleClass
{ Output
of this code will be: Hai Invalid String
Assignment In this case,
the assignments are explicit and you might not really know the significance
of as keyword. What if you have an array of Objects and you are trying
to assign each element of the object array to a string? Elements of the
array can either be an integer or a double or a string or even an instance
of another class. Because all value types and reference types are part
of Object. Now when you perform the assignment, at runtime it may end
up in exceptions. But using as keyword, instead of throwing exceptions
and halting the program it will assign the string value to null. Here
is an example to illustrate this case: class testClass{ Output of
this code will be: 100 cannot
be assigned to a string Note that
this keyword is used to perform type conversions only on reference types.
User-defined conversions cannot be performed using this keyword. Operator
Keyword is: In the above
example, you directly assign an object as string and later if the string
value is null then you come to know that it is an invalid assignment.
What if you get an option to check if the object is string before proceeding
with the assignment? You have this option using the operator keyword is.
Modified version of sampleClass using is keyword is mentioned below: class sampleClass
{ Output of
this code will be: The String
Values are: Hello There are
certain restrictions when you are using is keyword in your code: You
cannot overload this keyword
_______________________________________________________________________
FREE
Subscription
Subscribe
to our mailing list and receive new articles Note
: We never rent, trade, or sell my email lists to Visit
.NET Programming Tutorial Homepage ______________________________________________________ |