C # Basic Knowledge Series-13 Common Class Library (3)

Posted May 26, 20206 min read

0 . Foreword

In "C # Basic Knowledge Series-13 Common Class Library(2)", we introduced the contents of the two structures DateTime and TimeSpan, which is the simple operation of date and time in C #. This article will introduce Guid and Nullable.

1 . Guid structure

Guid(Globally Unique Identifier) is a string with a 128-bit binary length generated by an algorithm, but the length of the string is 36 of which 32 hexadecimal digits and four connectors. Its role is used to represent a globally unique identifier. When multiple systems or large amounts of data are used, it is used as a unique identifier, such as the primary key of a database. Guid is not unique to C #, so it can be used with confidence, without worrying about the embarrassing situation that the other party cannot recognize when interacting with other systems.

Guid is very widely used. If you have viewed the Windows system registry, you should have seen the following types of data:efa4bcc8-b293-48d5-9278-924b9c015b97. Guid is even used by Windows for component registration, network interface identification, etc.

In simple terms, Guid is suitable for scenarios that require no repeated identification.

1.1 Create a Guid

The creation of Guid is very simple and straightforward through Guid.NewGuid(), example:

class Program
    static void Main(string []args)
        Guid guid = Guid.NewGuid();

Running the above code multiple times will produce different results. This is the result of my one run:


At this point, creating Guid can be considered to achieve the goal, but let's take a look at the constructors of Guid:

public Guid(byte []b);

Initialize a Guid with a byte array of length 16, where the value of Guid is related to the byte array.(According to the definition, C # will convert the byte array b into 128-bit binary data, and then convert it into a string format).


class Program
    static void Main(string []args)
        var bytes = new byte [16]
        Guid guid = new Guid(bytes);

After multiple runs, the print results are the following:


As you can see from the above, a Guid element is created from a byte array, and the value of this element is the value of this byte array.

Continue to introduce the second construction method, created by formatted string:

public Guid(string g);

g represents Guid data, which has the following formats:

  1. dddddddddddddddddddddddddddddddd indicates 32 consecutive digits
  2. dddddddd-dddd-dddd-dddd-dddddddddddd represents the grouping of 8, 4, 4, 4 and 12 digits, which can be wrapped in parentheses and braces
  3. {0xdddddddd, 0xdddd, 0xdddd, {0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd}} Grouping of 8, 4, and 4 digits, and a subset of 8 groups of 2 digits Are prefixed with "0x" or "0X", separated by commas

This method accepts the Guid string in the above format. The following is an example:

string []guidStrings = {"ca761232ed4211cebacd00aa0057b223",
                         "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}"};
foreach(var guidString in guidStrings)
    var guid = new Guid(guidString);
    Console.WriteLine($"Original string:{guidString}");

The print result is as follows:


Initialize with the specified integer and byte array:

public Guid(int a, short b, short c, byte []d);

Where a represents the first four bytes, that is, the eight bits before the first separator, b represents the next two bytes, c represents the two bytes after b, and d represents the remaining eight bytes.

Guid(1,2,3, new byte []{0,1,2,3,4,5,6,7}) creates a Guid corresponding to "00000001-0002-0003-0001-020304050607".

Specify the values for each location in turn:

public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k);

This method is similar to the previous one, but it is more detailed, in which four bytes of int and one byte of byte are consistent with the actual byte length of the type.

1.2 An empty Guid

C # provides a static read-only attribute for the Guid structure:Empty, whose values are all zero, indicating the zero value of Guid. Many interfaces or systems will provide a default zero value for Guid-type fields. This is the value. In some business scenarios, you will encounter an equality judgment with the zero value.

1.3 A turn between the Guid and the string

According to the Guid constructor, you can see that Guid's print format should have three types, so how to generate these three types? Does C # have more format support?

Guid's ToString method has the following three versions:

public override string ToString();
public string ToString(string format);
public string ToString(string format, IFormatProvider provider);

The first is the default method for converting strings, the format is also introduced above. The last one involves internationalization, not to mention it. The second is to use the format to determine the output. The format value and corresponding meaning supported by C # are as follows:

Specifier Return value format
N 32 digits:00000000000000000000000000000000
D 32 numbers, separated by hyphens:00000000-0000-0000-0000-000000000000
B 32 bits, separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
P 32 bits, separated by hyphens, enclosed in brackets:(00000000-0000-0000-0000-000000000000)
X Four hexadecimal values enclosed in braces, where the fourth value is a subset of eight hexadecimal values (also enclosed in braces):{0x00000000, 0x0000, 0x0000 , {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}

If fomat is NULL or an empty string, the default is D.

Here introduces the method of Guid to generate the string and the corresponding format content, and there are two ways to convert the string to Guid in addition to using the constructor:

public static Guid Parse(string input);
public static Guid ParseExact(string input, string format);

The first method automatically parses the string format by C #, and the second method explicitly specifies the format of the string by the caller. The format only supports the five types of N/D/B/P/X.

2 . Basic type of cavitation

The basic data types we commonly use, including the types introduced in these two articles, are all struct types except string is a class. In C #, struct cannot be set to NULL, which generally does not affect the operation of the program. However, if it involves interaction, whether it is interacting with people or other systems, there will be situations where the data is not available. For example, a math test will have a numerical test score for each student. If a classmate misses the exam because of illness, it is obviously undesirable to mark him directly with a zero mark, so it needs to be marked as NULL, which means that the exam is missing. At this time, if you simply use int or double to save the score in the system, it will appear NULL and cannot be stored in the system.

In order to solve such problems, C # added Nullable , which is a structure, and C # added additional support for this. Let's see how to declare a nullable int type:

Nullable <int> score;

In addition to the above declaration method, C # also provides a special syntax, use ?:

int? score;

That is, type? Represents the nullable type of .

2.1 Use of nullable types

Nullable types can be used as normal as their original types, including arithmetic operations supported by the original types. However, it is worth noting that if the value of the controllable type is null, after calculating with other non-null values, the final result can only be null.

C # provides two properties for judging and reading values of nullable types:

public bool HasValue {get;}
public T Value {get;}

If HasValue is True, it means that Value can read the value correctly, otherwise the controllable type is null.

The above is an introduction to the use of Nullable. It is very simple to use, but this is a very important place in C #.

3 . Summary

This is the last article in the "C # Basic Knowledge Series-Common Class Library", but it does not mean that there are only so many common classes in C #, and there is still a lot of content behind. Rest assured, I will introduce you one by one in the future.

For more content, please pay attention to My Blog "Mr. Gao's Cabin"