C # Fields Study

Source: Internet
Author: User
Fields

A field is a variable that is associated with a class or with an instance of a class.

A field declared with the static modifier defines a static field. A static field identifies exactly one storage location. no matter how does instances of a class are created, there is only ever one copy of a static field.

A field declared without the static modifier defines an instance field. every instance of a class contains a separate copy of all the instance fields of that class.

In the following example, each instance of the color class has a separate copy of the R, G, and B instance fields, but there is only one copy of the black, white, red, green, and blue static fields:

Public class color
{
Public static readonly color black = new color (0, 0, 0 );
Public static readonly color white = new color (255,255,255 );
Public static readonly Color Red = new Color (255, 0, 0 );
Public static readonly Color Green = new Color (0,255, 0 );
Public static readonly Color Blue = new Color (0, 0,255 );

Private byte r, g, B;

Public Color (byte r, byte g, byte B ){
This. r = r;
This. g = g;
This. B = B;
}
}

As shown in the previous example, read-only fields may be declared with a readonly modifier.Assignment to a readonly field can only occur as part of the field's declaration or in a constructor in the same class.

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.