C#8.0 Essential Theory Chapter 2--Data Types

C#8.0 Essentials Chapter 2 – Data Types

2.1 Basic data types

C#'s basic data types have keywords associated with them. Decimal is a special floating-point number type that can store large numbers without representation errors.

2.1.1 Integer types

There are 8 integer types in C#

type size BCL name suffix
sbyte 8 bits System.SByte
byte 8 bits System.Byte
short 16 bit System.Int16
ushort 16 bit System.UInt16
int 32 bit System.Int32
uint 32 bit System.UInt32 U or u
long 64 bit System.Int64 L or l
head 64 bit System.UInt64 UL

All primitive types in C# have short names and full names. The full name corresponds to the type name in **BCL (Base Class Library)**, which is the same in all languages ​​and uniquely identifies the type in the assembly. logo. From the compiler's perspective, the final generated CIL code cannot tell which one is used in the source code. Don't alternate between short names and full names, such as string instead of System.String.

2.1.2 Floating point types

The precision of floating point numbers is variable. Unless the denominator happens to be an integer power of 2, the number cannot be accurately represented by the binary floating point type. For example, 0.1 can easily be represented as 0.09999999...or 0.10000...1.

type size BCL name Significant digits suffix
float 32 bit System.Single 7 F or f
double 64 bit System.Double 15-16 D or d

2.1.3decimal type

type size BCL name Significant digits suffix
decimal 128 bits System.Decimal 28-29 M or m

Unlike floating point numbers, the decimal type guarantees that all decimal numbers within the range are accurate, but its range is smaller and the calculation speed is slightly slower, but the difference is small and can be ignored. The reason m is used to represent decimal is because this data type is often used in monetary calculations.

2.1.4 Literal values

A literal value represents a fixed value in the source code. Putting the value directly into the source code is called hardcoding . By default, if you enter a literal value with a decimal point, the compiler will automatically interpret it as a double type. Integer values ​​usually default to a 32-bit int. If the value is too large, the compiler will interpret it as a long. In addition, the C# compiler allows assignment to non-int numeric classes, such as:

short s = 42;
byte b = 77;

This is only true for literal values, and the following is illegal:

b = s;

Sometimes the numbers are very large. In order to solve the readability problem, C#7.0 has added support for number separators , which can be separated by underscores (_) when writing literal values, such as 9_814_072_356

0x002A represents hexadecimal 42. Starting from C#7.0, numbers can be expressed as binary values. For example, 0b101010 represents 42. Starting from C#7.2, the number separator can be placed after x or b.

Numbers can be formatted in hexadecimal when output:

//输出0x2A,即十六进制的42
System.Console.Writeline($"0x{42:X}");

To more accurately represent the string form of a double value, you can use the format string and the round-trip format specifier R (or r) for conversion.

2.2 More basic types

2.2.1 Boolean type

type size BCL name
bool 8 bits System.Boolean

Although one binary bit is enough to hold a value of type Boolean, in C# bool is actually one byte in size .

2.2.2Character type

type size BCL name
char 16 bit System.Char

char represents a 16-bit character. Although the size is the same as ushort, char is a C#-specific type and must be treated separately (8-bit in C++).

Backslash and special character codes are collectively called escape sequences .

2.2.3 String

type BCL name
string System.String

A finite sequence of zero or more characters is called a string .

C# allows the @ symbol before a string to indicate that escape sequences are not processed and the result is a verbatim string literal . (Corresponding to raw string in C++11).

Unlike C++, C# does not automatically concatenate string literals. (Yes, "ab" and "cd" in C++ will automatically be concatenated into "abcd").

If the same string literal appears multiple times in an assembly, the compiler defines the string only once in the assembly and all variables point to it.

Verbatim and interpolation can be combined by specifying $ first and then @.

String interpolation is syntactic sugar for calling the string.Format() method, such as:

//表面上
System.Console.Writeline($"your name is {firstname},{lastname}.");
//实际上
object[] args = new object[] {firstname,lastname};
System.Writeline($"your name is {0},{1}.",args);

A certain degree of localization support is implemented, and post-compiled code injection will not be caused by strings.

Some string methods: Format, Concat, Compare, StartsWith, EndsWith, ToLower, ToUpper, Trim, TrimEnd, Replace.

Previously, calling static methods required namespace and type name prefixes. You can use the new using static directive in C# 6.0 to avoid these prefixes. Only static methods and properties are supported.

If you want to add actual left and right braces in an interpolated or formatted string, you can write two braces in succession, such as $"{ { {123} }}" for the string "{ 123 }".

The characters required for output newline are determined by the operating system. The newline character in Windows is a combination of \r and \n, while in UNIX it is a single \n.

Rely on System.WriteLine() and System.Enviroment.NewLine() instead\n to ensure cross-platform compatibility.

C# syntax allows you to access properties (Properties ) like member variables (called fields in C# ) . Properties define special methods called **assignment methods (setters) and value methods (getters)**

The key feature of the string type is that it is immutable . For performance reasons, it does not provide a mechanism to modify the content of the existing string. It is impossible to convert all the letters in the string to uppercase at the same memory location. It can only be used in other places. Create a new string in position so that it becomes an uppercase version of the old string, but the old string will not be modified.

If there are a large number of strings that need to be modified, consider using the System.Text.StringBuilder type instead of string.

2.2.4null and void

Assigning null to a reference type variable is different from not assigning a value at all. Assigning null to a string variable is not the same concept as assigning "" to the variable.

When declaring a variable, add a question mark after the name to indicate that the variable can be set to null. This is the nullable modifier (after C# 2.0).

Before C#8.0, the controllable modifier cannot be used for the declaration of reference type variables. Starting from C#8.0, there is the concept of nullable reference types. To enable it, you need to place "#nullable anywhere before declaring the variable. enable" statement. When enabled, setting a variable without a controllable modifier to null will generate a warning message.

void has two meanings: marking a method that does not return any value, and representing a pointer to a storage location of an unknown type, but this is relatively rare in C#.

2.3 Data type conversion

Any conversion that has the potential to cause data loss or throw an exception requires an explicit conversion. On the contrary, implicit conversion can be performed.

2.3.1 Display transformation

By default, data that cannot fit will quietly overflow during assignment, but placing the code in a checked block will cause a System.OverflowException exception to be thrown at runtime:

checked
{
	int n = inr.MaxValue+1;
}

Also supports unchecked blocks to force no overflow checking.

C# does not support efficient conversions from numeric types to boolean types to avoid possible ambiguities and to help prevent users from using the assignment operator when they should use the equality operator.

2.3.2 Implicit transformation

2.3.3 Type conversion without conversion operator

Each numeric data type contains a Parse() method , which allows you to convert a string into the corresponding numeric type. You can also use the special type System.Convert().

All types support the ToString() method.

Starting from C# 2.0, all primitive numerical types include the static TryParse() method . The difference from Parse() is that if the conversion fails, instead of throwing an exception, it returns false.

Starting from C#7.0, there is no need to first declare a variable that is only intended to be used as an out parameter. This variable can be used both inside and outside if.

Guess you like

Origin blog.csdn.net/Story_1419/article/details/132171922