Effective C # Principle 8: Ensure that 0 is valid for value-type data

Source: Internet
Author: User
Tags valid

. NET system defaults to 0 when all objects are initialized. This does not provide a way to prevent instances of value-type data created by other programmers from being initialized with 0. Please let the default value of your data type also be 0.

A special case is in the enumeration type data. Never create an enumeration type that does not include 0. All enumerated types are derived from System.ValueType. The value of the enumeration type starts at 0, but you can change the behavior:

public enum Planet
{
 // Explicitly assign values.
 // Default starts at 0 otherwise.
 Mercury = 1,
 Venus = 2,
 Earth = 3,
 Mars = 4,
 Jupiter = 5,
 Saturn = 6,
 Neptune = 7,
 Uranus = 8,
 Pluto = 9
}
Planet sphere = new Planet();

Sphere the value at this point is 0, and this is not a valid value. The value of an enumeration type is limited to all enumerated values, and any code that is lazy (ordinary) facts will not work. When you create your own values for your enumeration type, make sure that 0 is one of them. If your enumeration type uses a bit pattern, define 0 as a value when other properties do not exist.

In the current situation, you force the user to have to accurately initialize the value:

Planet sphere = Planet.Mars;

This makes it difficult to create other types that contain (Planet) this type:

public struct ObservationData
{
 Planet  _whichPlanet; //what am I looking at?
 Double _magnitude; // perceived brightness.
}

A user who creates a new Observationdata instance creates an illegal planet member:

ObservationData d = new ObservationData ();

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.