[Reading Notes] C # advanced programming Chapter 7 forced conversion of operators and types,

Source: Internet
Author: User

[Reading Notes] C # advanced programming Chapter 7 forced conversion of operators and types,




Arithmetic Operators


Logical operators

& | ^ ~ & |!

String concatenation operator


Increment and Decrement Operators

++ --

Shift Operator


Comparison Operators

=! = <> <=> =

Value assignment operator

= + =-= * =/= % = <<=> =

Member access operators (for objects and structures)


Index operator (used for arrays and indexers)


Type conversion Operator


Conditional operators (ternary operators)

? :

Delegate join and delete Operators


Object creation operator


Type Information operator

Sizeof is typeof

Overflow exception control operator

Checked unchecked

Indirect addressing Operator


Namespace alias qualifier


Null merge Operator


1,Simplified Operator

X + = y is equivalent to x = x + y. In the value assignment operator) all are in the same mode.

A single row of x ++ and ++ x is equivalent to x = x + 1. When they are used inside a long expression, the operator placed before (++ x) adds x before the expression.

Int x = 0, y = 0; x ++; ++ y; if (x = y) {Console. writeLine ("Single Row + + same result after previous");} if (++ x = 2) {Console. writeLine ("++ computed in advance");} if (y ++ = 2) {Console. writeLine ("++ is not computed in advance later ");}

Run the above Code and the result is as follows:



(1)Conditional Operators

Conditional operators (? :) Also known as the Unit operator, it is a simplified form of if... else. It determines whether a condition is true or false to return the corresponding value (true: the previous value, false: the subsequent value ).

Int x = 0; string str = x = 0? "X is equal to 0": "x is not equal to 0"; Console. WriteLine (str );

Run the above Code and the result is as follows:



Properly using the ternary operator can make the program very concise.

(2)Checked and unchecked Operators

C # provides the checked and unchecked operators to mark a code block and determine whether to perform an overflow check.

byte x = 255;x++;Console.WriteLine(x);

Run the above Code and the result is as follows:


This is because C # does not perform overflow checks by default using the unchecked operator, which will lead to data loss (the byte cannot exceed 255, and the overflow bit will be lost, so the result is 0 ).

To prevent data loss caused by overflow, you can use the checked operator to mark the code block.

byte x = 255;checked{    x++;}Console.WriteLine(x);

Run the above Code and the result is as follows:


The program will throw an exception. In this case, we can capture the exception to prevent overflow and data loss.

(3) is Operator

The Is operator checks whether the object Is compatible with a specific type (this type or derived from this type ).

Int x = 0; if (x is object) {Console. WriteLine ("x is object type or derived from object type ");}

Run the above Code and the result is as follows:


(4)As Operator

The as operator is used to perform explicit type conversion of the reference type. If the type to be converted is compatible with the specified type, the conversion succeeds. If not, the as operator returns null.

Object obj1 = "string"; object obj2 = 0; string str1 = obj1 as string; string str2 = obj2 as string; Console. writeLine ("obj1 as string Conversion Result:" + str1); Console. writeLine ("obj2 as string Conversion Result:" + str2 );

Run the above Code and the result is as follows:


The as operator allows secure type conversion in one step. You do not need to use the is operator to test the type before performing the conversion.

(5)Sizeof Operator

The sizeof operator can be used to determine the length of the stack's median type (in bytes ):


(6)Typeof Operator

The typeof operator returns a System. Type object of a specific Type. For example, if typeof (string) is returned, it indicates the Type of the System. String Type. This operator is useful when the reflection technique is used to dynamically search for object information.

(7)Can be null type and operator

If an empty type is used in a program, the impact of the null value on the use of various operators must be considered.

int? x = null;int? y = x + 1;//null

Possible expression of null value, cannot merge empty type and non-empty type in Expression

(8)Null merge Operator

Null merge operator (??) A shortcut is provided to indicate the possible null values when processing the null and reference types.


int? x = null;int y;y = x ?? 0;Console.WriteLine(y);

Run the above Code and the result is as follows:


If the first operand is null, the second operand is returned. Otherwise, the first operand is returned.


2,Operator priority

Descending priority from top to bottom



Primary Operators

(). [] X ++ x -- new typeof sizeof checked unchecked

Unary operator

+ -! ~ ++ X -- forced conversion of x and Data Type

Multiplication and division Operators


Addition and subtraction Operators


Shift Operator


Relational operators

<>>=< = Is

Comparison Operators

=! =

Bitwise AND operator


Bitwise XOR operator


Bitwise OR operator


Boolean AND operator


Boolean OR operator


Conditional Operators

? :

Value assignment operator

= + =-= * =/= % = <<==>>>>> =

We recommend that you use parentheses to explicitly specify the execution sequence of operators in complex expressions to make the code easier to understand.



(2)Type Security

1,Type conversion

(1)Implicit conversion

As long as the value does not change, the type conversion can be performed automatically (implicitly. The order of values is not affected, and implicit conversion can also be performed when the precision may be affected, because the compiler deems this an acceptable error.

(2)Explicit Conversion

When the value cannot be changed, explicit conversion is required. Otherwise, the compiler reports an error.


The long type cannot be implicitly converted to int type, but we can perform explicit conversion.

long lon = 1;int i = (int)lon;

Explicit conversion is a dangerous operation because it may cause overflow, resulting in different results from the correct values. When performing implicit conversion, you should use the checked operator for check.


2,Packing and unpacking

To convert a value type to a reference type.

int i = 100;object obj = i;

Binning is used to describe the opposite process. The previously boxed value type is forcibly converted back to the value type.

int i = 100;object obj = i;int _i = (int)obj;



(3)Comparison object equality

The mechanism for equality of objects varies depending on whether the reference type (instance of the class) is compared or the value type (basic data type, structure, or enumeration instance ).

1,Compare the equality of reference types

(1)ReferenceEquals () method

ReferenceEquals () is a static method to test whether two references reference the same instance of the class, especially whether the two references contain the same address in the memory. The most static method, which cannot be rewritten.

Person p1, p2; p1 = new Person (); p2 = new Person (); bool b1 = ReferenceEquals (null, null); bool b2 = ReferenceEquals (null, p1 ); bool b3 = ReferenceEquals (p1, p2); Console. result of WriteLine ("ReferenceEquals (null, null): {0}", b1); Console. result of WriteLine ("ReferenceEquals (null, p1): {0}", b2); Console. result of WriteLine ("ReferenceEquals (p1, p2): {0}", b3 );

Run the above Code and the result is as follows:


(2)Virtual Equals () method

The Equals () method is a virtual method, so you can rewrite it in your own class to compare objects by value.

(3)Static Equals () method

The Equals () static version has the same effect as the virtual instance version. The difference is that the static version has two parameters and compares them equally.

(4)Comparison operator =

It is better to regard the comparison operator as an intermediate option between strict Value Comparison and strict reference comparison.


2,Comparison Value Type equality

When comparing the equality of value types, use the same rule as the reference type: ReferenceEquals () is used to compare references, Equals () is used to compare values, and comparison operators can be considered as an intermediate option. But the biggest difference is that value types need to be boxed to convert them into reference types before they can be executed. The instance method Equals () is overloaded in the System. ValueType class to perform a proper equality test on the value type.


(4)Operator overload

To use an operator for a custom class, you must inform the compiler of the meaning of the operator in the context of the class. In this case, you need to use an operator overload.

C # requires that all Operator Overloading be declared as public and static, which means they are associated with their classes rather than specific instances. The operator keyword is required for heavy-duty operators. The compiler processes Operator Overloading and method overloading. C # requires a pair of reload comparison operators and must return a Boolean value.


public static decimal operator +(Person lhs, Person rhs){    return lhs.Money + rhs.Money;}

Operators that can be reloaded




Arithmetic binary Operators

+, *,/,-, And %


Arithmetic unary operator

+,-, ++, And ,--


Bitwise binary operator

&, |, ^, <,>


Bitwise unary Operators

! ,~ , True, false

The true and false operators must be reloaded in pairs.

Comparison Operators

= ,! =, >=, <, <=,>

Comparison operators must be reloaded in pairs.

Value assignment operator

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

You cannot explicitly reload these operators. When you override a single operator (such as + or-), they are implicitly overwritten.

Index Operators


You cannot directly reload the index operator. The member types of the indexer can support index operators in classes and structures.

Forced conversion operator of Data Type


You cannot directly overload the type forced operator. Forced conversion of user-defined types allows forced conversion of custom types.



(5)Forced conversion of user-defined types

C # Allow you to define your own data types (structures and classes), which means some tools are required to support type conversion between custom data types. The method is to define the forced type conversion operator as a member operator of the relevant class. The forced type conversion operator must be marked as implicit or explicit to show how to use it. We should follow the same rule as the predefined type forced conversion. If we know that type forced conversion is always safe no matter what value is stored in the meta variable, you can define it as implicit forced conversion. However, if some numeric values may fail, such as data loss or exception, the data type conversion should be defined as explicit forced conversion.


Explicit keyword explicit, implicit keyword implicit

Class Program {static void Main (string [] args) {Water water = new Water (100); Ice ice = (Ice) water; // The Water display is converted to Ice Water water2 = ice; // The Ice is implicitly converted to the Water Console. readKey () ;}} public class Water {public int Volume {get; set;} public Water (int volume) {this. volume = volume;} public static explicit operator Ice (Water lhs) {return new Ice (lhs. volume + 1) ;}} public class Ice {public int Volume {get; set;} public Ice (int volume) {this. volume = volume;} public static implicit operator Water (Ice lhs) {return new Water (lhs. volume-1 );}}

It is completely legal to define forced conversions between instances of different structures or classes, but there are two restrictions:

  • If a class is derived from another class, the type forced conversion between these two classes cannot be defined (the type conversion of these types already exists ).
  • Type forced conversion must be defined within the source or target data type.

C # Place the definition of forced type conversion within the source class (or structure) or target class (or structure. Its side effect is that the type forced conversion between two classes cannot be defined, unless at least the source code of one of the classes can be edited. This is because, this prevents third parties from introducing type conversion into the class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.