"Tutorial" "Reprint" C # Sharp Experience (Li Jianzhong)-02

Source: Internet
Author: User
Tags arrays empty exception handling expression garbage collection goto variables variable
Tutorial
The second part of the C # language Basic introduction

Nanjing University of Posts and Telecommunications Li Jianzhong (cornyfield@263.net)

Before you experience the sharpness of C #, the mastery of the basics of language is an essential part. Since many of the C # Basic languages originate from C + +, where only a brief introduction is made of those similar to C + +, we will experience focusing on the key language basics that are different from traditional C + +.
Data Type
The data types of the C # language are divided into two main categories: value types and reference types. Another data type "pointer" is set specifically for unsafe context programming, where the unsafe context refers to C # unmanaged code that unsafe the code to meet the direct operational requirements of the pointer to memory. This code will lose the CLR nature of the garbage collection of the Microsoft.NET platform, as we put it in the "COM Interop unmanaged programming and Exception handling" topic. The variables of a value type contain their data, and a variable of a reference type contains a reference or a handle to the memory block that contains the data. The difference between the two can be clearly seen from the following picture:

A possible problem with reference types is that when multiple variables refer to the same block of memory, modifications to any one of the reference variables cause the value of that object to change. A null value indicates that the reference type does not refer to any actual address.
Value types can be divided into struct types and enumeration types. struct types include simple types and user-defined structure types. Enumeration types and user-defined struct types we will elaborate on the topic "Nineth lecture structure, enumeration, array and string". Simple types can be divided into Boolean and numeric types. Boolean types in the C # language are strictly distinguished from numeric types, with only true and false two values, and no conversions between other types, as in C + +. Numeric types include integer values, floating-point and decimal three types. The integer value type has a total of nine Sbyte,byte,short,ushort,int,uint,long,ulong,char. In addition to the char type, the other 8 kinds of 221 groups are signed and unsigned respectively. Floating point values have float and double two species. Decimal is mainly used in financial, monetary and other computing environments with higher accuracy requirements. The following table is a detailed description of these simple types:

Simple Type
Description
Sample
SByte
8-bit signed integer
SByte val = 12;
Short
16-bit signed integer
Short val = 12;
Int
32-bit signed integer
int val = 12;
Long
64-bit signed integer
Long val1 = 12; Long val2 = 34L;
Byte
8-bit unsigned integer
byte val1 = 12; byte val2 = 34U;
UShort
16-bit unsigned integer
ushort Val1 = 12; ushort Val2 = 34U;
UInt
32-bit unsigned integer
UINT VAL1 = 12; UINT VAL2 = 34U;
ULong
64-bit unsigned integer
ULONG Val1 = 12; ULONG val2 = 34U; ULONG Val3 = 56L; ULONG Val4 = 78UL;
Float
32-bit single-precision floating-point numbers
float val = 1.23F;
Double
64-bit double-precision floating point numbers
Double val1 = 1.23; Double val2 = 4.56D;
L
Boolean type
bool Val1 = true; BOOL Val2 = false;
Char
Character type, Unicode encoding
Char val = ' h ';
Decimal
28 128-bit Decimal types for valid digits
Decimal val = 1.23M;
Reference types are divided into four types: classes, interfaces, arrays, delegates. Class except that we can define our own types, we include two more specific types of object and string. Object is the inherited root class for all types in C #, including all value types and reference types. The string type is a sealed type (cannot be inherited), its instance represents a Unicode string, and the array type we will put in the Nineth lecture structure, enumerations, arrays, and strings. The interface type defines a contract for a method that we will describe in the seventh interface inheritance and polymorphism. A delegate type is a signature that points to a static or instance method, similar to a function pointer in C + +, which is described in the eighth delegate and event. In fact, we'll see from the later topics that these types are some form of wrapper for the class.
Each data type has a corresponding default value. The default value for a numeric type is 0 or 0.0, where char defaults to ' \x0000 '. The default value for a Boolean type is false. The default value for the enumeration type is 0. The default value for a struct type is to set the field of all its value types to the default value of the corresponding value type, and to set the field of its reference type to NULL. The default value for all reference types is null.
Different types of data can be converted between, C # type conversion has implied conversion, clear conversion, standard conversion, custom conversion A total of four ways. Implicit conversions, like explicit conversions and C + +, data from the "small type" to "large type" conversion for implicit conversion, from the "large type" to "small type" conversion to a clear conversion, a clear conversion requires such as "(type) data" general bracket conversion operator. Standard conversions and custom transformations are for both system-built and user-defined transformations, both for custom types such as classes or structs.
variables and Constants
A variable represents a storage location, and a variable must have a determined data type. One of the meanings of C # 's type safety is to ensure that the stored location of the variable holds the appropriate type. You can divide variables in C # into static variables, instance variables, pass-value parameters, reference parameters, output parameters, array parameters, and local variables in seven different ways. A local variable is a temporary variable in the body of the method. <
Static variables and instance variables are primarily for data members (also called domains) within a class or struct. Static variables are stored after the class or struct type it hosts is loaded, and if they are not initialized, the initial value of the static variable will be the default value held by its type. An instance variable obtains storage space after its instance of the class is created, and its initial value is the same as the definition of a static variable if it is not initialized. The two are described in more detail in the "Sixth domain method properties and indexers" topic.
Pass-value parameters, reference parameters, output parameters, and array parameters are mainly for the parameter types of the method. A simple argument is a transfer of the value of a variable, and the change within the method does not work outside the method. The change in the data member that refers to the reference (handle) variable in the method, i.e. the actual memory block, will remain unchanged outside the method body, but the change in the reference (handle) itself does not work for a slightly different variable in which the value parameter itself is a reference type. A reference parameter is a passing of a handle to a variable, and any changes within the method to that variable are persisted outside the method body. The output parameter is C # specifically tailored for a method with multiple return values, similar to a reference variable, but not initialized before entering the method body, while other parameters require explicit initialization in C # in the method body. Array parameters are designed specifically to pass a large number of array elements, which is essentially a reference variable's pass-value parameter. They are described in more detail in the topic "The sixth domain method attribute and indexer".
Local variables are strictly speaking in C # block statements, for statements, switch statements, variables declared within the using statement, and its lifecycle is strictly limited within these statement blocks.
A constant determines its value at compile time and is not allowed to be modified throughout the program. A constant declaration must be assigned a value at the same time. Because of its compile-time attribute that determines values, reference types may have values that can only be string and null (except for strings, the builder of a reference type must be at run time to determine the value of a reference type).
Operators and Expressions
C # retains all the operators of C + +, where the pointer operator (* and->) and the reference operator (&) require a unsafe context. C # abandoned the scope discrimination operator (::), all changed to a single point operator (.). We no longer elaborate on those retained C + + operators, here are mainly introduced in C # has a special meaning of several operators: As,is,new, Typeof,sizeof,stackalloc.
The as operator is used to perform conversions between compatible types, and the as operator results in NULL when the conversion fails. The IS operator is used to check whether the Run-time type of an object is compatible with a given type, or false if the expression is not null and can be converted to a specified type. The AS and is operators are designed based on the same type of identification and conversion, both of which have similar applications. Actually expression as type is equivalent to expression is type? (type) expression: (type) null.
As new for the operator is used to create objects and invoke constructors on the heap, it is noteworthy that value type objects (such as structs) are created on the stack, and reference type objects (such as classes) are created on the heap. New is also used for modifiers that hide inherited members of base class members. To hide inherited members, declare the member in a derived class with the same name and modify it with the new modifier. The typeof operator is used to obtain a System.Type object of a certain type, and we will describe it in detail with the Microsoft.NET type system in the tenth lecture feature and mapping. The sizeof operator is used to obtain the size, in bytes, of a value type that does not apply to a reference type. Stackalloc is used to allocate a block of memory on the stack, valid only in the initializer of a local variable, similar to the _alloca of the C + + language. Both sizeof and statckalloc require unsafe contexts because of direct operations involving memory.
Some of the operators in C # can be overloaded like C + +. Operator overloading enables custom types (classes or structs) to easily express certain commonly used operations with simple operators.
The combination of a series of operators and operands that completes a computed result is called an expression. As with C + +, C # expressions can be divided into assignment expressions and Boolean expressions, C # does not introduce a new form of expression, we no longer repeat.
Namespaces and Statements
C # uses namespaces (namespace) to organize programs. namespaces can be nested. A using indicator can be used to simplify a reference to a namespace type. The using indicator has two uses. "Using System;" Statement allows us to replace the type "System.Console" with the short type name "Console". "Using Output = System.Console;" Statement allows us to replace the type "System.Console" with the alias "Output". The introduction of namespaces greatly simplifies the way in which C # programs are organized.
C # statements can be divided into label statements, declaration statements, block statements, empty statements, expression statements, selection statements, repeated statements, jump statements, try statements, checked/unchecked statements, lock statements, using statements.
The label statement mainly for Goto jump design, C # does not allow cross method jumps, but allows small-scale methods within the jump. The declaration statement can initialize the assignment at the same time, and the object's instantiation declaration requires a new keyword. Block statements use "{" and "}" to define statement blocks, mainly to define the scope of local variables. An empty statement is expressed in C # with a semicolon ";" that does not have execution semantics. An expression statement constitutes a statement through an expression.
The selection statement has both the IF statement and the switch statement, identical with C + +. Repeated statements, in addition to while,do,for three loops, introduce a foreach statement to traverse all elements of the collection, but this requires specific interface support, which we'll elaborate on later in this chapter.
The jump statement has break,continue,goto,return,throw five kinds of statements, the first four are the same semantics as C + +, and the throw statement and the subsequent try statements are described in the 11th Lecture COM Interop unmanaged programming and exception handling.
The checked/unchecked statement is used primarily for the context of overflow checking in numeric operations. The lock statement is primarily used for lock control of the thread semaphore. The using statement is used primarily for fragment resource management. We will have specific implications in the following chapters.


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.