Improve C # program 50 Methods clause 8: ensure that 0 is a valid value type

Source: Internet
Author: User

The default initialization mechanism of the. NET system sets all objects to 0 [14]. We cannot block other value types.ProgramMembers Initialize all their members to 0 [15]. Therefore, we should use 0 as the default value of the value type.

Enumeration is a typical case. The enumerated type we created should never regard 0 as invalid. We know that all enumeration types inherit from system. valuetype. The default enumeration value starts from 0, but we can change this default behavior.

Public Enum planet

{

// Explicitly assign values.

// Otherwise, the default value starts from 0.

Mercury = 1,

Venus = 2,

Earth = 3,

Mars = 4,

Jupiter = 5,

Saturn = 6,

Neptune = 7,

Uranus = 8,

Pluto = 9

}

Planet sphere = new planet ();

Here, sphere is 0, which is obviously invalid. In this way, the enumerated values must be in the predefined set.Code(This is usually the case. Therefore, when creating our own enumerated values, make sure that 0 is valid. If we use the bitwise mode to define the enumerated value, we should define 0 as "excluding all other attributes ".

According to the current situation, we should force the user to explicitly initialize the enumerated value:

Planet sphere = planet. Mars;

However, this makes it difficult for such an enumeration type to be a member of the Value Type:

Public struct observationdata

{

Planet _ whichplanet; // What is it?

Double _ magnitude; // brightness.

}

When an observationdata object is created, an invalid planet field is obtained:

Observationdata d = new observationdata ();

The _ magn1_value of the newly created observationdata object is 0, which is reasonable. But _ whichplanet is invalid. We need to make 0 a valid state. If possible, we 'd better use 0 as the default value. The planet Enumeration type does not have an obvious default value. It makes no sense to set a planet value if you do not have a clear choice. In this case, we can explicitly express 0 as an uninitialized value to facilitate subsequent updates to it:

Public Enum planet

{

None = 0,

Mercury = 1,

Venus = 2,

Earth = 3,

Mars = 4,

Jupiter = 5,

Saturn = 6,

Neptune = 7,

Uranus = 8,

Pluto = 9

}

Planet sphere = new planet ();

Now sphere contains a none value. Adding this uninitialized default value to the planet enumeration will have some impact on the observationdata structure. The newly created observationdata object will contain a _ magnqueue with a value of 0 and A _ whichplanet with a value of none. At this time, we should add an explicit constructor to support the Explicit initialization of all fields:

Public struct observationdata

{

Planet _ whichplanet; // What is it?

Double _ magnitude; // brightness.

Observationdata (planet target,

Double mag)

{

_ Whichplanet = target;

_ Magn133 = mag;

}

}

However, remember that the observationdata still has a default constructor. You can still use the default constructor to create the variable "initialize the system". We cannot prohibit the user from doing so.

Before discussing other value types, we need to talk about some special rules for applying enumeration types as bit flag. The enumerated type using the flags feature should always set the value of none to 0:

[Flags]

Public Enum styles

{

None = 0,

Flat = 1,

Sunken = 2,

Raised = 4,

}

Many developers use the bitwise AND operator to mark enumeration values in place. If the value is 0, a serious problem occurs. If the flat value is 0, the following test will always be false:

If (flag & styles. Flat )! = 0) // If flat = 0, it will always be false.

Doflatthings ();

If flags is used, make sure that 0 is in valid state and the meaning is "not including all other flag cases ".

If the value type contains a reference type, another common initialization problem occurs. String inclusion is a common situation:

Public struct logmessage

{

Private int _ errlevel;

Private string _ MSG;

}

Logmessage mymessage = new logmessage ();

The _ msg field of the mymessage object will be an empty reference. We have no way to force other initialization, but we can use attributes to limit this issue to the type. We can create an attribute to expose the _ MSG value to all customers of the type, and add logic to the attribute so that it returns a "string with blank content ", instead of an empty reference:

Public struct logmessage

{

Private int _ errlevel;

Private string _ MSG;

Public String message

{

Get

{

Return (_ MSG! = NULL )?

_ MSG: String. empty;

}

Set

{

_ MSG = value;

}

}

}

We should use this attribute within the type. In this way, empty reference check can be concentrated in one place. When called from our Assembly, the message accessors are almost certainly inline. When we get efficient code, we also minimize errors.

In summary, the system initializes all instances of the value type to 0. There is no way to prevent users from creating value-type instances with "all fields are 0. If possible, we should take "All fields are 0" as the default value of the type. As a special case, the enumeration type marked with bits should make sure that 0 means "not including all other tags ".

 

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.