. NET (C #) Internals: Little-known??

Source: Internet
Author: User

. NET (C #) Internals: Little-known?? From Blog Garden-Home Original essence area Author: Wu Qin

READ: 19 Comments: 0 Author: Wu Qin posted on 2010-05-21 16:09 original link

--To see the truth in detail. Introduction

"??" I knew it a long time ago, but I never wanted to share it. The main reason is that it should be very basic, we all know, but now I find that many people around me do not know "??" This operator. So there is this article, if you have the right?? It is not necessary to read this article when you are familiar with it. The main contents of this article are as follows: 1, "??" Operator 2, nullable type 3, in-depth analysis 4, Comparison 1, "??" Operator

If "??" The left operand of the operator is not NULL, and the operator returns the left operand, otherwise the right-hand operand is returned. The format is as follows:

X = A?? B

It's obviously a two-dollar operator. If A is not empty, x=a; otherwise x=b. Let's take a look at the following example:

Using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Csharptest
{
Class Program
{
static void Main (string[] args)
{
int a = 0;
int b = a?? -1;
System.Console.WriteLine (b);
}
}
}

What do you think it will output? It will not output anything because a compile-time error occurs. You will see an error as shown in the following illustration:

Figure 1, "??" Compile-time error

Yes, as prompted by "??" The operands on either side of the operator cannot be int type. This is why. Let's analyze it. This is because value types are not nullable, such as int I can be i=100, or, 0 or, or-1, but not i=null. Let's look at the following code:

Using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Csharptest
{
Class Program
{
static void Main (string[] args)
{
String a= "yes";//if a=null, then B'll equal to "no"
String B = a?? "No";
System.Console.WriteLine (b);
}
}
}

We run this code to get the output "yes" ("no" is output if a=null). This is because the reference type can be null. 2. Nullable type

So is it "??" Operators can only be applied on reference types. Or what we think should be done on value types, such as int. This will use a nullable type . A nullable type is an instance of a system.nullable structure. A nullable type can represent a value within the normal range of its underlying value type, plus a null value. For example, Nullable<int32>, read as "Nullable Int32", can be assigned to any value from 2147483648 to 2147483647, or it can be assigned a value of null . Nullable<bool> can be assigned a value of true or false, or null. The ability to assign null to a numeric type or Boolean is particularly useful when working with databases and other data types that contain elements that may not be assigned values. For example, a Boolean field in a database can store a value of true or false, or the field may not be defined.

But for the sake of simple grammar T? is the shorthand for system.nullable<t>, where t is the value type. The two forms are interchangeable. That is, int? is equivalent to system.nullable<int>. Now let's look at the following code:

Using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Csharptest
{
Class Program
{
static void Main (string[] args)
{
Int? x = 1;//if X=null, then y would equal to-1. If you don ' t believe, can try!
int y = x?? -1;
System.Console.WriteLine (y);
}
}
}

So we can use the int type "??" operator. The code above will output 1.

Nullable types have the following characteristics:

A nullable type represents a variable of a value type that can be assigned a null value. Cannot create a nullable type based on a reference type. (reference type has supported null values.) )。

The syntax T is shorthand for system.nullable<t>, where t is a value type. The two forms are interchangeable.

Assign values to nullable types the same way you assign values to a generic value type, such as int? x = 10; or double? d = 4.108;.

If the value of the underlying type is null, use the System.Nullable.GetValueOrDefault property to return the value or default value assigned by the underlying type, such as int j = X.getvalueordefault ();

Use the HasValue and value read-only property to test for null and retrieve values, such as if (x.hasvalue) j = x.value;

If this variable contains a value, the HasValue property returns True, or False if the value of this variable is null.

If the value is assigned, The Value property returns it, or the System.InvalidOperationException is thrown.

The default value of the nullable type variable sets HasValue to false. Valueis not defined.

Use the ??? operator to assign a default value that is applied to non-null types when the current value is empty, such as int? x = null; int y = x?? -1;

Nested nullable types are not allowed. The following line of:nullable<nullable<int>> N will not be compiled; 3, in-depth analysis

We use ILDASM to look at the last piece of code and know that the IL code for the main function is:

Figure 2, main function IL code

From the red circle labeled 1 above, we can see that the nullable type is still a value type. The red circle labeled 2 is the judgment "??" The left operand of the operator has a value of Get_hasvalue (), and then the red circle labeled 3 evaluates the return value: If the return value of Get_hasvalue () is not 0 (true), then branching to the target instruction at the specified offset is about to return "??" The left-hand operand of the operator is a red circle labeled 4 GetValueOrDefault (), otherwise the right-hand operand is returned.

As we can see from the diagram above, the main operations involved are the methods and attributes in the system.nullable structure, and the Get_hasvalue for the properties in System.Nullable Structures GetValueOrDefault () Is the method in the System.Nullable structure (refer to MSDN).

If you are using ILDASM to view the front "??" Operators are applied to the IL code of a string, these methods and properties are not involved, as shown in the following illustration:

Figure 3, "??" The operator applies to the IL code of the string 4, comparing

Actually "??" Operator is equivalent to:

if (a!=null)
X = B;
Else
X = C;

But if you use the "??" Operators are simpler, such as determining whether a TextBox with an ID of txtID is empty and returning its text if it is not empty, otherwise generating a new textbox. You can write this:

string result = (txtID?? New TextBox ()). Text;

What's more, the previously mentioned nullable type applies to the database using the "??" operator is simpler.

"??" Does the operator also make you get to the "?:" Ternary operator first. The format of the "?:" ternary operator is as follows:

X = A? B:C;

Here A is a Boolean expression, X=a if A is true; otherwise x=c. Because the "?:" ternary operators originated in the C-System programming language, we are more familiar with, here is not in-depth.

I hope this article brings you the information.

http://anforen.5d6d.com/

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.