C # basic knowledge analysis can be empty type

Source: Internet
Author: User

Introduction:

In C #2.0, the void type is also introduced. The Void type is also the value type, but the void type includes the null value type, the following describes the specific support for the null type in C #2.0 (I have been thinking about how to share this article recently, at first, I thought it was relatively simple to use the void type, and I thought it was unnecessary. But considering the integrity of this series, I decided to give it a sigh of relief, hope to be helpful to some unfamiliar people ).

I. Why is there an empty type?

If my friends read my previous shares, they will not be unfamiliar with this part, because I usually introduce C # features that often start with this method, because each feature has its own cause (there is a buddhist saying: Everything has a reason, and there is a result ), first of all, let's talk about this cause (the new feature of the null type is added, of course .), When designing a database, we can set the database field to allow null values. If the database field is a date and so on, when the C # language is a value type, when we map a database table to an object, the Datetime type cannot be null in the C # language. If this happens, it will conflict with the database design, in this way, developers will have this requirement-can the value type be empty? At the same time, Microsoft also saw that the user had such a requirement. Therefore, Microsoft added a new type in C #2.0, that is, the null type, that is, the value type containing the null value, this is the reason I understand. After introducing the reason, of course, it's just a bit boring. What is the empty type?

II. Introduction to the null type

It is also a value type, but it is a value type that contains null. We can use the following expression to indicate the null type (I believe everyone is familiar with it ):

Copy codeThe Code is as follows: int? Nullable = null;

The above code is int? It is an int type that can be empty (some people may have such questions. What should I do if I want to make a value type a null type in C #1? Of course, this can be done before C #1, but it will be quite troublesome. If you are interested, you can dig the root "? "This modifier is only a syntactic sugar provided by C # (the so-called syntactic sugar is a convenient form provided by C #. In fact, there must be no int? This type, this int? The compiler considers the Nullable <int> type to be null ), actually, the null type provided by true C #2.0 is -- Nullable <T> (this T is the generic parameter described in the previous topic, where T can only be the value type, because the optional null types are defined as: public struct Nullable <T> where T: struct) and Nullable. The following code describes the use of the null type:

Copy codeThe Code is as follows: namespace can be empty type Demo
{
Class Program
{
Static void Main (string [] args)
{
// The following code can also define an int like this? Value = 1;
Nullable <int> value = 1;

Console. WriteLine ("outputs with Null Types and values :");
Display (value );
Console. WriteLine ();
Console. WriteLine ();

Value = new Nullable <int> ();
Console. WriteLine ("outputs with null type and no value :");
Display (value );
Console. Read ();
}

// Output method to demonstrate the use of methods and attributes in the null type
Private static void Display (int? Nullable)
{
// HasValue indicates whether a null object has a value.
// When using the Value attribute, you must first determine whether the null type has a Value,
// If the HasValue of an empty object returns false, an InvalidOperationException is thrown.
Console. WriteLine ("Whether the null type has a value: {0}", nullable. HasValue );
If (nullable. HasValue)
{
Console. WriteLine ("Value: {0}", nullable. Value );
}

// GetValueOrDefault (it indicates that if a null object has a value, it will be returned with its value. If a null object does not contain a value, the default value 0 will be returned.) It is equivalent to the following statement.
// If (! Nullable. HasValue)
//{
// Result = d. Value;
//}

Console. WriteLine ("GetValueorDefault (): {0}", nullable. GetValueOrDefault ());

// The GetValueOrDefault (T) method indicates that if the HasValue attribute is true, it is the Value of the Value Attribute; otherwise, it is the Value of the defaultValue parameter, that is, 2.
Console. WriteLine ("GetValueorDefalut overload method use: {0}", nullable. GetValueOrDefault (2 ));

// GetHashCode () indicates the hash code of the object returned by the Value Attribute if the HasValue attribute is true. If the HasValue attribute is false, it is zero.
Console. WriteLine ("use of the GetHashCode () method: {0}", nullable. GetHashCode ());
}
}
}

Output result:

The above DEMO code is commented out, and I will not explain it here. To help you understand that the null type is a value type, the intermediate language code is shown below:

3. null merge operator (?? Operator)

?? The operator is the "null merge operator", which indicates two operands. If the number on the left is not null, the number on the left is returned. If the number on the left is null, returns the number on the right. This operator can be used for a null type or a reference type, but cannot be used for a value type (the value type cannot be applied here except for the null type ), because ?? The number on the left must be compared with null. However, the value type cannot be compared with null, so it is not supported ?? Operator), the following uses an example to hide it ?? Use of operators (?? This operator makes it easy to set the default value. It can avoid writing if and else statements in the Code and the number of simple codes, which is helpful for reading .)

Copy codeThe Code is as follows: static void Main (string [] args)
{
Console. WriteLine ("?? The use of operators is as follows :");
NullcoalescingOperator ();
Console. Read ();
}

Private static void NullcoalescingOperator ()
{
Int? Nullable = null;
Int? Nullhasvalue = 1;

//?? Similar to the functions of the three-object Operator
// The following code is equivalent:
// X = nullable. HasValue? B. Value: 12;
Int x = nullable ?? 12;

// At this time, nullhasvalue cannot be null, so the Value of y is nullhasvalue. Value, that is, output 1
Int y = nullhasvalue ?? 123;
Console. WriteLine ("null type without value: {0}", x );
Console. WriteLine ("null type with value: {0}", y );

// Simultaneously ?? Operators can also be used to reference types. The following is an example of a reference type.
Console. WriteLine ();
String stringnotnull = "123 ";
String stringisnull = null;

// The following code is equivalent:
// (Stringnotnull = null )? "456": stringnotnull
// The following code is also equivalent:
// If (stringnotnull = null)
//{
// Returned "456 ";
//}
// Else
//{
// Return stringnotnull;
//}
// From the above equivalent code, we can see that there is ?? A large number of if-else statements can be omitted after the operator, so that the code is less readable.
String result = stringnotnull ?? "456 ";
String result2 = stringisnull ?? "12 ";
Console. WriteLine ("when the reference type is not null: {0}", result );
Console. WriteLine ("when the reference type is null: {0}", result2 );
}

The running result is as follows:

Iv. Empty packing and unpacking

The value type contains the packing and unpacking process, and the empty type also belongs to the value type, which also involves the packing and unpacking process. Here we first introduce the concepts of packing and unpacking, packing refers to the process from the value type to the reference type. unpacking is, of course, the reverse process of packing, that is, the process from the reference type to the value type (here I will further explain the packing and unpacking I understand, first. the Net value type is allocated on the stack. However, when the reference type is assigned to the managed stack, the packing process copies the value type value from the push stack to the managed stack, the stack is then pushed to store the reference to the copy value on the managed stack. However, the box is to copy the value on the managed stack to the stack. simply put, packing and unpacking are a process of copying values. Just like moving something from one place to another, we have a deep understanding, you can refer to the blog in the Lower Garden .), the process of packing and unpacking that I understand is in brackets. The following describes how to unpack and unboxing empty types:

When an empty type is assigned to a reference type variable, the CLR will pack the Nullable object, first, CLR checks whether the null type is null. If it is null, CLR does not perform the actual packing operation (because null can be directly assigned to a reference type variable ), if the value is not null, CLR obtains the value from an empty type object and boxed the value (this process is the packing process of the value type .), When a boxed value type is assigned to an empty type variable, the CLR will unpack the boxed value type. If the referenced value type is null, in this case, the CLR sets the null type to null (if you think it is too long, you can directly read the following code, and the code will also have detailed comments ). The following is an example to demonstrate the use of empty packing and unpacking. This helps you better understand the concepts described above:

Copy codeThe Code is as follows: static void Main (string [] args)
{
// Console. WriteLine ("?? The use of operators is as follows :");
// NullcoalescingOperator ();
Console. WriteLine ("Empty packing and unpacking are used as follows :");
BoxedandUnboxed ();
Console. Read ();
}

// Demonstration of empty packing and unpacking
Private static void BoxedandUnboxed ()
{
// Define an empty type object nullable
Nullable <int> nullable = 5;
Int? Nullablewithoutvalue = null;

// Obtain the type of an empty object. System. Int32 is returned instead of System. Nullable <System. Int32>.
Console. WriteLine ("the null type of the retrieved non-null can be: {0}", nullable. GetType ());

// An exception occurs when calling a method of the null type. Therefore, before calling a method of the referenced type, it is recommended that you first check whether the method is null.
// Console. WriteLine ("the null type can be obtained: {0}", nullablewithoutvalue. GetType ());

// Assign an empty type object to the reference type obj. The boxing operation will take place. You can use boxed in IL to prove it.
Object obj = nullable;

// Obtain the reference type after packing. At this time, the output is still System. Int32, instead of System. Nullable <System. Int32>
Console. WriteLine ("Get the boxed obj type: {0}", obj. GetType ());

// Unpack the variable into a non-empty variable
Int value = (int) obj;
Console. WriteLine ("unboxing into non-empty variables: {0}", value );

// Unpack the box to empty Variables
Nullable = (int ?) Obj;
Console. WriteLine ("unboxing into empty variables: {0}", nullable );

// Bind an empty object with no value
Obj = nullablewithoutvalue;
Console. WriteLine ("whether obj is null: {0} After null can be boxed", obj = null );

// Unbox the variable into a non-empty variable. In this case, an NullReferenceException is thrown because obj is equal to null after no value can be empty and an empty address is referenced.
// It is equivalent to assigning the null value to an int type variable after unpacking. Of course, an error will occur.
// Value = (int) obj;
// Console. WriteLine ("when a non-empty variable is undefined, it is: {0}", value );

// Unpack the box to empty Variables
Nullable = (int ?) Obj;
Console. WriteLine ("Whether the empty variable is null: {0}", nullable = null after the empty type is packed );
}

Running result:

The above code has been commented out, and the code is relatively simple. I will not explain it here, in fact, empty packing and unpacking operations can be understood as a non-empty packing and unpacking process, but for non-empty type because it contains null values, therefore, CLR checks whether it is null in advance. If it is null, no processing is required. If it is not null, binning and unboxing are performed according to the non-null packing and unboxing processes.

V. Summary

The introduction of this topic is complete. This topic mainly introduces the knowledge about the null type and the null type, I hope this article will help you better understand the empty type. Next topic will introduce it to you.Anonymous MethodThe anonymous method is also a foreshadowing of Lambda expressions and Linq, but it was proposed in C #2, as a result, it can be seen that the addition of Lambda and Linq in C #3.0 was actually planned by Microsoft as early as C #2.0 and long ago (this is also my inference, however, I don't think it was proposed to put Lambda and Linq both in C #2, but in C #3.0, I understand the reasons for this: 1. I think Microsoft was definitely trying to propose it together, but later I found that these new features will make major changes to the compiler, it takes a long time to implement it. At this time, the user may not be able to wait and feel that C # does not have many things. Therefore, Microsoft will release the completed part first, however, put Lambda and Linq in C #3. I think it should be like this, so all the features of C # are closely linked .)

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.