Operators


The following table lists the C# operators.

Category

Operator

Arithmetic

+-*/%

Logical

&|^~&&||!

String concatenation

+

Increment and decrement

++ --

Bit shifting

<< >>

Comparison

== != < > <= >=

Assignment

=+=-=*=/=%=&=|=^=<<=>>=

Member access (for objects and structs)

.

Indexing (for arrays and indexers)

[]

Cast

()

Conditional (the Ternary Operator)

?:

Object Creation

new

Type information

sizeof (unsafe code only) is typeof as

Overflow exception control

checked unchecked

Indirection and Address

*->& (unsafe code only) []

Java developers will immediately spot that C# operators are very similar to Java's. However, there are a few significant differences.

To determine whether an object belongs to a given class or any of the parent classes Java uses the instanceof operator. The C# equivalent of instanceof is the is operator. It returns true if the runtime type of the given class is compatible with the specified type. Here's an example of its use:

 string y = "a string"; object x = y; if(x is System.String) { System.Console.WriteLine("x is a string"); } 

Also, because Java has no value types other than the primitives whose size is always known, there is no real use for a sizeof operator. In C#, value types range from primitives to structs to enums. As with Java, the size of the primitives is known. There is a need, however, to know how much space a struct type or enum type occupies. This is what the sizeof operator is for. The syntax is quite simple: sizeof(<ValueType>), where <Value Type> is the struct or enum. Note that sizeof may only be used in an unsafe context. The sizeof operator cannot be overloaded.

The typeof operator is used to get an instance of a type's System.Type object without having to create an instance of the type. In Java, every type has a public static class variable that returns a handle to the Class object associated with that class. The typeof operator provides this type of functionality. Just as you saw with sizeof, the syntax is very simple. The statement typeof(<Type>) where <Type> is any user-defined type will return you the type object of that type.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net