Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

From the author of

Other Operators

C# has some operators that can't be categorized as easily as the other types. These include the is, as, sizeof(), typeof(), checked(), and unchecked() operators. The following sections explain each operator.

The is Operator

The is operator checks a variable to see if it's a given type. If so, it returns true. Otherwise, it returns false. Here's an example.

int i = 0;
bool isTest = i is int; // isTest = true

The as Operator

The as operator attempts to perform a conversion on a reference type. The following example tries to convert the integer i into a string. If the conversion were successful, the object variable obj would hold a reference to a string object. When the conversion from an as operator fails, it assigns null to the receiving reference. That's the case in this example, where obj becomes null because i is an integer, not a string:

int i = 0;
object obj = i as string;
Console.WriteLine("i {0} a string.", 
  obj == null ? "is not" : "is" ); // i is not a string.

The sizeof() Operator

C# provides a facility to perform low-level functions through a construct known as unsafe code. The sizeof() operator works only in unsafe code. The operator takes a type and returns the type's size in bytes. Here's an example:

unsafe 
{
  int intSize = sizeof(int); // intSize = 4
}

The typeof() Operator

The typeof() operator returns a Type object. The Type class holds type information about a value or reference type. The typeof() operator is used in various places in C# to discover information about reference and value types. The following example gets type information on the int type:

Type myType = typeof(int);
Console.WriteLine(
  "The int type: {0}", myType ); // The int type: Int32

The checked() Operator

The checked() operator detects overflow conditions in certain operations. The following example causes a system error by attempting to assign a value to a short variable that it can't hold:

short val1 = 20000, val2 = 20000;
short myShort = checked((short)(val1 + val2)); // error

The unchecked() Operator

If it is necessary to ignore this error and accept the results regardless of overflow conditions, use the unchecked() operator, as in this example:

short val1 = 20000, val2 = 20000;
short myShort = 
  unchecked((short)(val1 + val2)); // error ignored

TIP

Use the /checked[+|-] command-line option when the majority of program code should be checked (/checked+) or unchecked (/checked-). Then all that needs to be done inside the code is to annotate the exceptions with the checked() and unchecked() operators.

  • + Share This
  • 🔖 Save To Your Account