The operators commonly used in C# include conditional operators, is operators, as operators, typeof operators, etc. Next, in the article, we will introduce the usage methods of each operator in detail.
Conditional operator
The conditional operator is represented by ( ?: )
condition ? X:Y
The above statement indicates that if the condition is true?, then X: otherwise, Y
Conditional operators can be called ternary operators and are a simplified form of if..else. First, judge a condition first. If the condition is true, return the first value, otherwise return the second value. appropriate
The use of ternary operators can make the program more concise.
as operator
The as operator represents a cast, and no exception is thrown even if the conversion fails. The following two issues need to be paid attention to
(1) It can only be used for reference types
(2) Return null value when the conversion is unsuccessful
example:
object a = "str"; object b = 5; string c = a as string;//The return is string string d = b as string;//The return isnull
is operator
The is operator is used to determine whether the variable is of a specific type or is derived from this type. If it is, it returns true, otherwise it returns false.
example:
int a=1; bool type = a is long;
Returns false because int is not long and is not derived from long
typeof operator
The typeof operator is a type used to return class, and can also be used for open generic types. Types with multiple type parameters must have the appropriate number of commas in the specification.
Type a = typeof(AAA); AAA aa = new AAA(); Type b = ()
Note: typeof and GetType() have the same function, the difference is that the parameter of typeof is type, and the parameter of GetType() is a variable of type
sizeof operator
The sizeof operator is the length (units: bytes) required to return the value type in the stack.
int a = sizeof(int); // 4
int is 32 bits, accounting for 4 bytes, and 1 byte is 8 bits
Note: sizeof is generally used to obtain the number of bytes occupied by basic types (integral, floating point number, character type, boolean type)
Summary: The above is the entire content of this article, I hope it will be helpful to everyone.