Chapter 4 C # Types
Since you already know how to create a simple C # program, then I will introduce you to the type system of the C #. In this chapter, what you learned how to use different values and reference types, plus boxes and framework mechanisms can do for you. Although this chapter does not focus on the example, you can also learn a lot of important information about how to create a program using the ready-to-class type.
4.1 value type
Various value types always contain a value of the corresponding type. C # forces your initialization variables to use them to calculate - the variable is not initialized, because when you try to use them, the compiler will tell you.
This value is actually copied whenever a value is assigned to a value type. Compared to the reference type, it is only copied by the reference, and the actual value remains in the same memory location, but now there are two objects to point to it (reference it). The value type of C # can be classified as follows:
· Simple Types
· Structure type (Struct Types)
· Enumeration Types
4.1.1 Simple Type
Simple types that appear in C # share some features. First, they are all the alias of the .NET system type. Second, a constant expression consisting of simple types is only checked only when compiling. Finally, the simple type can be initialized by literal. The following is a C # simple type class:
· Integer
Boolean
· Character type (a special case of integer)
· Floating point
· Decimal type
4.1.1.1 Integer
There are 9 integers in C #. Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, and Char (discussed separate section). They have the following features:
The Sbyte type represents a symbol 8-bit integer, with a value range between -128 to 127.
· ByTET type represents no symbol 16-bit integer, with a value between 0 and 255.
· The Short type represents a symbol 16-bit integer, with a value between -32, 768 ~ 32, 767.
The Ushort type represents no symbol 16-bit integer, with a value between 0 and 65, 535.
The INT type represents a symbol 32-bit integer, with a value range between -2, 147, 483, 648 ~ 2, 147, 483, 647.
· The UINT represents no symbol 32-bit integer, with a value between 0 to 4,294,967,295.
• The Long type represents 64-bit symbolic integers, with a value range between -9, 223, 372, 036, 854, 775, 808 ~ 9, 223, 372, 036, 854, 775, 807.
• Ulong is 64-bit unsigned integers, with a value between 0 to 18, 446, 744, 073, 709, 551, 615.
VB and C programmers may be surprised by the new range represented by the INT and Long data types. Compared to other programming languages, in C #, int is no longer depends on the size of a machine (Word), and long is set to 64 bits.
4.1.1.2 Boolean
The Boolean data type has two Boolean values of True and False. You can assign a RUE or FALSE value to a Boolean variable, or an expression can also be assigned to a variable, which is equal to the value of the expression:
BOOL BTEST = (80> 90);
Compared to C and C , in C #, the TRUE value is no longer any non-zero value. Don't convert other intersive into a block in order to increase convenience.
4.1.1.3 characters
The character is a single Unicode character. A Unicode character is 16-bit, which can be used to represent most languages in the world. You can assign a character variable as follows:
Char chsomechar = 'a';
In addition, the variable can be assigned (prefix / u): char chsomechar = '/ x0065' by hexadecimal escar (prefix / x) or Unicode representation: char chsomechar = '/ x0065';
Char chsomechar = '/ u0065';
There is no implicit conversion to convert char to other data types. This means that a character variable is used as another integer data type as another integer data type - this is another aspect of the C. programmer must change the habit. However, explicit conversion can be used:
Char chsomechar = (char) 65;
INT nsomeint = (int) 'a';
There is still an escap (character meanings) in C. To change your brains, see Table 4.1.
Table 4.1 Escap Sequences
Essential character name / 'single quotes / "double quotation mark // anti-slope / 0 empty characters / A exclamation number / B retractor / F change page / N new row / R Enter / T horizontal Tab / V vertical Tab
4.1.1.4 floating point
Two data types are used as floating point: float and double. Their difference is to take value range and accuracy:
FLOAT: The value ranges between 1.5x10-45 ~ 3.4x1038, the accuracy is 7 digits.
Double: The value ranges between 5.0x10-324 to 1.7x1030, the accuracy is 15 ~ 16 digits.
When the operation is performed with two floating-point types, the following values can be generated:
Zheng zero and negative zero
Endless and endless
Non-digital value (not-a-number, abbreviation NAN)
Non-zero value limited set
Another computation rule is that all other types are converted into floating point to perform operations when a value in the expression is a floating point.
4.1.1.5 Decimal Type
The decimal type is a high-precision, 128-bit data type, which is intended for the calculation of financial and currency. It is represented by about 1.0 x 10-28 to 7.9x1028, with 28 to 29 valid numbers. It is to be noted that the accuracy is expressed as a decimal number (DIGITS). The calculation is most accurate to 28 digits after the decimal point.
As you can see, Decimal's value range is narrower than Double, but it is more accurate. Therefore, there is no implicit conversion between decimal and double - a directional conversion may overflow, and the precision may be lost to another direction. You have to use explicit conversion.
When defining a variable and assigning it, use the M suffix to indicate that it is a decimal type:
Decimal DecmyValue = 1.0m;
If M is omitted, it will be subject to a Double type before the variable is assigned.
4.1.2 Structure Type
A structural type can declare constructor, constant, static field, method, attribute, index, operator, and nested type. Although the listed features look like a mature class, in C #, the difference between structures and classes is that the structure is a value type, and the class is a reference type. Compared to C , you can define a class with a structural keyword.
The main idea of using the structure is to create small objects such as Point and FileInfo, and more. You can save memory because there is no additional reference to the same reference. For example, this will cause great difference when declaring arrays of thousands of objects.
Listing 4.1 contains a simple structure named IP that represents an IP address of 4 fields using the Byte type. This does not include a method, because these work is just like the class, will be described in detail in the next chapter. Listing 4.1 Define a simple structure
1: USING System;
2:
3: Struct IP
4: {
5: Public BYTE B1, B2, B3, B4;
6:}
7:
8: Class Test
9: {
10: public static void main ()
11: {
12: ip myip;
13: Myip.b1 = 192;
14: myip.b2 = 168;
15: myip.b3 = 1;
16: myip.b4 = 101;
17: Console.write ("{0}. {1}.", Myip.b1, myip.b2);
18: Console.write ("{0}. {1}", myip.b3, myip.b4);
19:}
20:}
4.1.3 Enumeration Type
When you want to declare a unique type consisting of a specified constant collection, the enumeration type is what you want to find. The simplest form, it looks like this:
ENUM MONTHNAMES {January, February, March, April};
Because I used default settings, the enumeration element is an int type, and the first element is 0 value. Each continuous element is incremented by 1. If you want to assign a value directly to the first element, you can set it below 1:
ENUM MONTHNAMES {January = 1, February, March, April};
If you want to give an intention to give each element - even the same value - this is also no problem:
ENUM MONTHNAMES {January = 31, February = 28, March = 31, April = 30};
The final choice is different from the data type of int. Can be assigned in this statement:
ENUM MONTHNAMES: BYTE {January = 31, February = 28, MARCH = 31, April = 30};
The type you can use is limited to Long, Int, Short, and Byte.
4.2 Reference Type
Compared with the value type, the reference type does not store the actual data they represent, but they store references for actual data. Provides the following reference types in C # to use:
· Object type
· Class type
·interface
· Representative Yuan
· String type
· Array
4.2.1 Object Type
The object type is all types of mother - it is the most fundamental base class for other types. Because it is the base class of all objects, any type of value can be assigned to it. For example, a integer:
Object theobj = 123;
Give all C programmers a warning: Object does not equal your void * that you may be looking for. In any case, forget the pointer is always a good idea.
When a value type is fed (as an object utilized), the object type is used. This chapter will discuss the box and fill the box later.
4.2.2 Class Type
A class type can contain data members, functions members, and nested types. Data members are constants, static fields, and events. Functions include methods, attributes, indexes, operators, constructor, and destructors. The functions of classes and structures are very similar, but as mentioned earlier, the structure is a value type and the class is a reference type.
Compared to C , only single inheritance is allowed. (You can't have a multi-base class that derive a new object.) However, a class in C # can be derived from multiple interfaces, which will be described in the next section.
Chapter 5 "Class" special discussion use class programming. This section is only intended to give an overview of the C # class suitable type diagram. 4.2.3 interface
An interface declares a reference type of abstract members. Similar concepts in C is a structure of a structure, and the method is equal to 0. If you don't understand these concepts at all, here is what the interface is actually done in the C #. It only has method names, but there is no code at all. This suggests that you cannot instantiate an interface, you can only instantiate an object derived from the interface.
Method, attributes, and indexes can be defined in an interface. So, what is the speciality of the interface? When defining a class, you can derive your own interface, and you can derive from only one class.
You may ask: "OK, but I have to implement all the interface members, then what can I get from this way?" I want to give an example from .NET: Many classes implement the IDictionary interface. You can use a simple type to convert access interfaces:
IDictionary mydict = (idictionary) SomeObjectthatsupportsit;
Now your code can access the dictionary. Also, I said that many classes can implement this interface - so you can reuse the code in multiple places to access the IDictionary interface! Once you have learned, you can use anywhere.
When you decide to use an interface in class design, learn more about object-oriented design is a good idea. This book can't teach you these concepts, but you can learn how to create an interface. The following code segment defines the interface ifce, it only has one method:
Interface iFace
{
Void ShowmyFace ();
}
As I mentioned, you cannot instantiate an object from this definition, but you can derive a class from it. Therefore, this class must implement the ShowmyFace abstract method:
Class CFace: Iface
{
Public void showmyface ()
{
Console.writeLine ("Implementation");
}
}
The difference between interface members and class members is that interface members cannot be implemented. Therefore, I don't want to mention this again in the next chapter.
4.2.4 Representative Yuan
Representative meta encapsulates methods with certain names. Basically, representative meta is a security version (callback function) of type security and function pointer. Static and instance methods can be simultaneously packaged in a representative element example.
Although you can use a representative as a method, its main use is to have a class event. Again, I want to introduce you to the next chapter, where you will discuss classes in detail.
4.2.5 String Type
C programmers may be surprised, but of course, C # has a basic string type for operating string data. The string class is derived directly, and it is sealed, which means that you can't derive classes from it. Just like other types, strings are an alias for predefined class System String.
Its usage is very simple:
String mystring = "some text";
The merge string is equally simple:
String mystring = "Some text" "and a bit more";
And if you want to access a single character, what you want to do is access to the subscript:
Char chfirst = mystring [0];
When comparing if the two strings are equal, simply use the "==" comparison operator.
IF (MyString == YourString) ...
I just want to mention it, although the string is a reference type, but the comparison is a comparison value, not a comparison reference (memory address). In every example of this book, almost all of the string types, and in these routines, I will introduce you to some extreme interesting methods that are revealed by string objects.
4.2.6 array
An array contains variables accessed by calculating the subscript. All variables contained in arrays and as elements must be the same type. This type is naturally called "array type". Arranges can store integer objects, string objects, or any object you propose.
The number of dimensions of the array is the so-called row, which determines the number of related array elements. The most common array is a one-dimensional array (first row). A multi-dimensional array has a ranks greater than 1. The subscript of each dimension starts at 0, and finally the length of the dimension is 1.
There should be sufficient theoretical support. Let's take a look at an array initialized with an array initializer:
String [] arrlanguages = {"c", "c ", "c #"};
This shorthand effect is equivalent to:
Arrlanguages [0] = "c"; arrlanguages [1] = "C "; arrlanguages [2] = "c #";
The compiler has done all your work. Of course, it will work with the multi-dimensional number of initializer:
INT [,] arr = {{0, 1}, {2, 3}, {4, 5}};
It is below:
Arr [0,0] = 0; Arr [0, 1] = 1;
Arr [1,0] = 2; Arr [1, 1] = 3;
Arr [2,0] = 4; Arr [2, 1] = 5;
If you don't want to initialize an array in advance, I know its size, the statement is like this:
Int [,] myarr = new int rt [5, 3];
If the size of the array must be dynamically calculated, the statement used to array can be written like this:
INT nVAR = 5;
int [] arrtoo = new int [nvar];
As I started in this section, you can send anything in the array, as long as all element types are the same. So if you want to put anything in an array, declare its type as an object:
4.3 Pixabay
In this chapter, I have given a wide range of value types and reference types. Due to the speed of the speed, you will use value types - they just occupy a certain memory block. However, sometimes the convenience of objects is as good as the type value type.
Pixabay and fill the core concept of the C # type system, then debut. This mechanism forms a bundled connection between value types and reference types by allowing a value type to convert into a type object or from a type ¯. Anything is an object - however, this is just when they need them as an object.
4.3.1 Bring box conversion
Give a value box refers to implicitly converting any value type to a type object. When a value type is fetched, an object instance is assigned, and the value of the value is copied to a new object.
See the following example:
Int nfunny = 2000;
Object ofunny = nfunny;
The assignment of the second line hints to call a boxed operation. The value of the NFunny integer variable is copied to the Ofunny object. Now the integer variables and object variables are exist at the same time in the stack, but the value of the object remains in the heap.
So, what does it impose? Their values are independent of each other - there is no connection between them. (Ofunny does not quote the NFunny value.) The following code descriptions:
Int nfunny = 2000;
Object ofunny = nfunny; Ofunny = 2001;
Console.writeline ("{0} {1}", nfunny, OFNNY;
When the code changes the value of Ofunny, the value of NFunny has not changed. As long as you have this COPY action in your head, you can use the value of the value of the value of the value to play your huge advantage!
4.3.2 Filing Conversion
Compared with the box, the box is an explicit operation - must tell the compiler, and you want to extract which value type from the object. When a fax operation is performed, the C # detects the requested value type is actually stored in an object instance. After successful confirmation, this value is filled.
This is how the box is executed:
Int nfunny = 2000;
Object ofunny = nfunny;
INT nnotsofunny = (int) OFNNY;
If you are wrong, request a Double value
Double nnotsofunny = (double) OFNNY;
Communication Runtime, Simmon Language Runtime will trigger an invalidcastexception exception. You can learn more about exception handling in Chapter 7 "Exception Handling" in Chapter 7.
4.4 small knot
In this chapter, you learned the types used in C #. Simple value types include integer, Boolean, floating-point and decimal types. You will use some types frequently, perform mathematics and finance, and logical expression.
Before introducing the reference type, I showed a structure type that looks like class. It is almost like a class, but it is just a value type, which makes it more suitable for a large number of small objects.
The reference type starts on the Objedt itself of all objects. Object is the base class of all objects in C #, and it is equally used in the fax and fills of the value type. In addition, I also allow you to appreciate the representative meta, string and array.
Let C # programmers are very kind of type. It is C # object-oriented heart, the next chapter specializes in making you quickly understand this exciting and powerful type.