C # Basic Knowledge Comprehensive parsing nullable type _c# tutorial

Source: Internet
Author: User
Tags anonymous type null

Introduction:

In C # 2.0, nullable types are also introduced, nullable types are value types, but nullable types are value types that include NULL, and the following is a description of what the support for nullable types is in the next c#2.0 (I've been thinking recently about how to share this article, Because the beginning to feel that the use of nullable type is relatively simple, feel that there is no need to speak, but in view of the integrity of this series, the decision or nagging, I hope that some people do not know how to help.

One, why there are nullable types

If my friends had seen my share before, I would not be unfamiliar with this part, because I generally introduce C # features often start in this way, because every feature has a reason for it (there is a Buddhist language that says: Everything has a cause, there is a cause), first of all, to say this reason ( The result is, of course, a new feature that adds a nullable type. When we design a database, we can set the database field to allow null values, and 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 is not NULL in the C # language. If this would conflict with the design of the database, then developers would have the need-can value types also be nullable types? At the same time, Microsoft also saw that users have such a demand, so Microsoft in C # 2.0 added a new type-nullable type, that is, the value of a null value type, which is what I understand the reason, after the introduction of the cause, of course, is a good nagging under the nullable type is what thing?

Second, the introduction of nullable types

A nullable type is also a value type, except that it is a value type that contains null. We can express the nullable type as follows (I'm sure everyone is not unfamiliar):

Copy Code code as follows:

Int? nullable = NULL;

above code int? is the nullable int type (someone may be so doubtful, if in the c#1 I want to make a value type a nullable type how to do?) Of course this can be done before the c#1, but it will be quite troublesome, for this if interested friends can go to dig the root, but in fact "?" This modifier is just a syntactic candy provided by C # (the so-called grammatical sugar, which is a convenient form provided by C #, in fact there is no int?) This type, this int? compiler thinks is nullable<int> type, can be empty type), actually true C # The nullable type provided by 2.0 is--nullable<t> (this t is the generic parameter of the previous presentation, where t can only be a value type, since the definition of a nullable type is: public struct nullable<t> where T: struct) and nullable. Here's a piece of code to describe the use of nullable types:

Copy Code code as follows:

Namespace Nullable type Demo
{
Class Program
{
static void Main (string[] args)
{
The following code can also define int like this? value=1;
nullable<int> value = 1;

Console.WriteLine ("Nullable type has a value output condition:");
Display (value);
Console.WriteLine ();
Console.WriteLine ();

Value = new nullable<int> ();
Console.WriteLine ("Output without value of nullable type:");
Display (value);
Console.read ();
}

Output methods that demonstrate the use of methods and properties in nullable types
private static void Display (int. Nullable)
{
The HasValue property represents whether a nullable object has a value
You must first determine whether a nullable type has a value when you use the Value property.
A InvalidOperationException exception is thrown if the hasvalue of a nullable type object returns False
Console.WriteLine ("Nullable type has value: {0}", nullable.) HasValue);
if (nullable. HasValue)
{
Console.WriteLine ("Value: {0}", nullable.) Value);
}

GetValueOrDefault (indicates that if a nullable object has a value, it is returned with its value, and if the nullable object does not contain a value, the default value of 0 is returned) rather than the following statement
if (!nullable. HasValue)
// {
result = D.value;
// }

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

The GetValueOrDefault (T) method represents the value of the Values property if the HasValue property is true, otherwise the DefaultValue parameter value, that is, 2.
Console.WriteLine ("Getvalueordefalut overloaded method uses: {0}", nullable.) GetValueOrDefault (2));

GetHashCode () represents the hash code of the object returned for the Value property if the HasValue property is true, or zero if the HasValue property is False
Console.WriteLine (Use of the "GetHashCode () method: {0}", nullable. GetHashCode ());
}
}
}

Output results:

The above demo code is commented, here is no longer explained, in order to let you understand the further understanding of the nullable type is a value type, the following is a screenshot of the intermediate language code:

Three, empty merge operator (?? operator

?? The operator is the null merge operator. It means two operands, and if the number on the left is not NULL, it returns the number on the left and, if the left number is NULL, returns the number on the right, which can be used for nullable types or reference types, but not for value types ( Value types cannot be applied (here except nullable types) because?? operator to compare the number on the left with NULL, whereas a value type cannot be compared to a null type, so it is not supported. operator), the following is an example to cover up?? The use of the operator (?? This operator allows us to set the default value to avoid writing if, else statements in the code, the number of simple code, thus conducive to reading. )

Copy Code code as follows:

static void Main (string[] args)
{
Console.WriteLine ("?? Operators are used as follows: ");
Nullcoalescingoperator ();
Console.read ();
}

private static void Nullcoalescingoperator ()
{
Int? nullable = NULL;
Int? Nullhasvalue = 1;

// ?? Similar to the function of the three-mesh operator.
So the following code is equivalent to:
X=nullable. Hasvalue?b.value:12;
int x = nullable?? 12;

Nullhasvalue cannot be null at this time, so the value of Y is nullhasvalue. Value, that is, output 1
int y = nullhasvalue?? 123;
Console.WriteLine ("Nullable type has no value: {0}", x);
Console.WriteLine ("Nullable type has a value: {0}", y);

At the same time?? Operators can also be used for reference types, and the following are examples of reference types
Console.WriteLine ();
String stringnotnull = "123";
string stringisnull = null;

The following code is equivalent to:
(Stringnotnull ==null)? "456": Stringnotnull
The following code is also equivalent to:
if (stringnotnull==null)
// {
return "456";
// }
Else
// {
return stringnotnull;
// }
From the above equivalent code can be seen, there are?? Operators can omit a large number of if-else statements, so that the code is less, natural readability is high
string result = Stringnotnull?? "456";
String result2 = Stringisnull?? "12";
Console.WriteLine ("Reference type is not NULL: {0}", result);
Console.WriteLine ("Case of reference type null: {0}", RESULT2);
}

Here is a screenshot of the results of the run:

Box and unboxing of nullable types

A value type has a boxing and unboxing procedure, and a nullable type is also a value type. There is also the process of boxing and unboxing, which first introduces the concept of boxing and unboxing, boxing refers to the process from the value type to the reference type, the unboxing of course is the reverse process of boxing, that is, from the reference type to the value type process ( Here's a further explanation of the boxes and unboxing I understand, first. NET medium value types are allocated on the stack, whereas reference types are allocated on the managed heap. The boxing process is to copy value-type values from the push stack onto the managed heap, and then the stack stores a reference to the copy value on the managed heap, but the unboxing is the copy of the value on the managed heap onto the stack. A simple statement, Boxing and unboxing are a process of copying a value, just like moving, moving things from one place to another, for in-depth understanding, you can refer to the blog post in the park. In parentheses, I understand the boxing and unboxing process, the following is a specific description of the nullable type of boxing and unboxing:

When a nullable type is assigned to a reference type variable, the CLR then boxing the nullable type (nullable<t>) object, first the CLR detects whether the nullable type is NULL, and if NULL, The CLR does not do the actual boxing operation (because NULL can be assigned directly to a reference type variable), and if not for NULL,CLR, the value is fetched from the nullable type object and boxed (the process is the boxing process of the value type). , when a boxed value type is assigned to a nullable type variable, the CLR then splits the boxed value type, and if the boxed value type reference is NULL, the CLR sets the nullable type to null (if it is verbose, you can see the following code directly, Detailed comments are also available in the code. Here is an example to illustrate the use of boxed and unboxing of nullable types to help you better understand the concepts described earlier:

Copy Code code as follows:

static void Main (string[] args)
{
Console.WriteLine ("?? Operators are used as follows: ");
Nullcoalescingoperator ();
Console.WriteLine ("Nullable type of packing and unboxing is used as follows:");
Boxedandunboxed ();
Console.read ();
}

Demonstration of nullable type boxing and unboxing
private static void Boxedandunboxed ()
{
Defines a nullable type Object nullable
nullable<int> Nullable = 5;
Int? Nullablewithoutvalue = null;

Gets the type of the Nullable object, which returns System.Int32 instead of System.nullable<system.int32> this is something you should pay special attention to.
Console.WriteLine ("Gets the type of non-nullable nullable type: {0}", nullable.) GetType ());

An exception occurs when invoking a method for a null type, so it is generally preferable to have a habit of detecting whether it is null before invoking the method of a reference type.
Console.WriteLine ("The type of the nullable type to get Null is: {0}", Nullablewithoutvalue.) GetType ());

To assign a nullable type object to the reference type obj, a boxing operation occurs, and you can prove by boxed in the IL
Object obj = nullable;

Gets the type of the boxed reference type, at which point the output is still System.Int32, not system.nullable<system.int32>
Console.WriteLine ("Get boxed obj type: {0}", obj.) GetType ());

Unboxing into a non-empty variable
int value = (int) obj;
Console.WriteLine ("The case of unpacking as a Non-empty variable is: {0}", value);

Unboxing into nullable variables
nullable = (int?) Obj
Console.WriteLine ("Unboxing into nullable variables: {0}", nullable);

Boxing an object of a nullable type with no value
obj = Nullablewithoutvalue;
Console.WriteLine ("Obj is null:{0} after boxing null nullable type}", Obj==null);

Unboxing into a non-nullable variable, a NullReferenceException exception is thrown, because obj equals null after a nullable type with no value is boxed, referencing an empty address
This is equivalent to assigning a null value to a variable of type int after unpacking, and of course there is an error.
Value = (int) obj;
Console.WriteLine ("When a nullable type without a value is boxed, the case for a non-empty variable is: {0}", value);

Unboxing into nullable variables
nullable = (int?) Obj
Console.WriteLine ("A nullable type with no value boxed, unboxing into nullable variable is null:{0}", nullable = = null);
}
Run Result:

There are comments in the code above, and the code is simpler, this is not explained here, in fact, nullable types of boxing and unboxing operations can be understood as a Non-nullable value type of boxing and unboxing process, but for non-null type because contains null value, so the CLR will check it in advance of whether it is empty, Is null without any processing and, if not null, boxing and unboxing according to a non-nullable value type's procedure for boxing and unboxing.

V. Summary

  Here the introduction of this topic is completed, this topic mainly introduces the next nullable types and the relevant knowledge of nullable types, I hope this article can help you to the understanding of nullable types can be more comprehensive, the next topic will be introduced under anonymous method , Anonymous methods are also a foreshadowing of lambda expressions and LINQ, however, it was presented in C#2 to see that the Lambda and LINQ were added in C # 3.0, which was planned by Microsoft as early as C # 2.0, and was already planned (which is also my inference, But I don't think it's directly in the C # 2 that you put both Lambda and LINQ, but in C # 3.0 put forward, I understand why there are--1 think Microsoft was sure to want to put together, but later found that the new features of the compiler will make a larger change, Need a relatively long time to achieve, at this time and afraid of users can not wait, think C # A lot of things do not, so Microsoft first put the good part of the first release, but the Lambda and LINQ put to c#3 to put forward. I reasoned that this should be the case, so all the features of C # are tightly connected. )

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.