C #: Create a constant, atomic value type

Source: Internet
Author: User
Tags constant zip

Overview

This is the seventh section of the book "Effective C #" reading notes. Through this article, I would like to tell you about a problem that we may not notice at ordinary times: Create a value type that is constant and atomic.

Starting from the type design

From class to struct

If we are going to design a type that stores the address of the recipient, we call this a type. It should contain such several attributes:

Province Province

City

Zip zip code

Require control of the ZIP format (must be all numbers, and 6-bit), how should we design it? I think a lot of people will write this:

public class Address {
    private string province;
    private string city;
    private string zip;

    public string Province {
       get { return province; }
       set { province = value; }
    }

    public string City {
       get { return city; }
       set { city = value; }
    }

    public string Zip {
       get { return zip; }
       set {
           CheckZip(value);  // 验证格式
           zip = value;
       }
    }

    // 检测是不是正确的 zip
    private void CheckZip(string value) {
       string pattern = @"d{6}";
       if(!Regex.IsMatch(value, pattern))
           throw new Exception("Zip is invalid! ");
    }
    public override string ToString() {
       return String.Format("Province: {0}, City: {1}, Zip: {2}", province, city, zip);
    }
}

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.