Basic knowledge of C #: Basics (11) value types, reference types

Source: Internet
Author: User
C # is an object-oriented language, in object-oriented thinking, only objects, all things can be described by the class. So for example, these, int,bool,char,string,double,long, etc. are all classes, so like, 30,2.5, "test" is an object of the corresponding class.

        static void Main (string[] args)        {            string istring = 30.ToString ();            String dstring = 2.5.ToString ();            String sstring = "Test". ToString ();            Console.WriteLine (String. Format ("{0},{1},{2}", Istring, Dstring, sstring));            Console.ReadLine ();        }

Output:

You can see that they have the ToString () method, so they are objects.
When writing code, defining the data type must have been used in addition to the above:

         static void Main (string[] args)        {            Int32 i = 0;            UInt32 j = 0;            String str = "Test";            Console.ReadLine ();        }

This is actually. NET is a mechanism that. NET is a platform that has c#,vb these languages. So. NET defines a series of types that are mapped to different languages, and Int32 is int in C #. Such data types are called primitive types, and objects in the class in C # must be built using new. This part of the class can be represented directly by constants. Primitive types are defined in the. NET Framework, under the System namespace. Look at type mappings for primitive types in the C # language.

. NET Framework Primitive Types

C # types

Range of values Note

System.Boolean

bool

True/false /
System.Byte Byte 0 ~255

Unsigned 8-bit integer

System.SByte SByte -128 ~ 127 Signed 8-bit integer
System.Char Char 0 ~ 65,535 Unsigned 16-bit integer
System.Int16 Short

-32,768 ~ 32,767

Signed 16-bit integer
System.UInt16 UShort 0 ~ 65,535 Unsigned 16-bit integer
System.Int32 Int -2,147,483,648 ~ 2,147,483,647 Signed 32-bit integer
System.Int64 Long

-9,223,372,036,854,775,808 ~

9,223,372,036,854,775,807

Signed 64-bit integer
System.UInt64 ULong

0 ~ 18,446,744,073,709,551,615

Unsigned 64-bit integer
System.Single Float

±1.5x10-45 ~±3.4x1038

(7 significant digits)

32-bit single-precision floating-point number
System.Double Double

±5.0x10-324 to ±1.7x10308

(15 to 16 significant digits)

64-bit double-precision floating point
System.Decimal Decimal

±1.0x10-28 to ±7.9x1028

(27 to 28 significant digits)

128-bit floating-point number
System.String String Arbitrary string /
System.UInt32 UInt 0 ~ 4,294,967,295 Unsigned 32-bit integer

Except string in the table is a reference type (explained separately), others are value types.
The following is a brief description of the reference type and value type.
There is a heap and stack concept when learning C language.
Heap area--the programmer allocates the release, or the program ends with an OS recycle, which is distributed in a similar way to a linked list.
Stack area--Automatically allocated by the compiler to release, store the function parameter value, variable value and so on.
Stack memory structure can quickly allocate memory and reclaim memory, but the stack space is limited, excessive use will "overflow", so the stack only allocates the commonly used, small space-occupying data type, heap memory structure allocation memory is slow, but the use of large space, can store large data.
In C #, basically all of the data is stored in the heap structure, called the managed heap, and monitored by. NET garbage collection. However, the efficiency of memory allocation is relatively low in the stack structure. In order to properly recycle, the heap space allocated each time is slightly larger than the actual space required, small data use heap is not appropriate.
You can look at value types and reference types in comparison:
C # provides a struct-defined value type that allocates memory directly on the stack.

 <summary>//////Use a struct to define a value type,///value type can only implement interface, cannot inherit class///</summary> public struct Structpositi venumber:icloneable {//<summary>///value Type field///</summary> private int Nu        Mber; <summary>///static read-only field, as the initial value of the class///</summary> public readonly static Structpositivenumb        Er initialvalue = new Structpositivenumber ();            <summary>//Properties///</summary> public int Number {get            {return number;                 } set {if (value <= 0) {throw new Exception ();            } this.number = value; }}///<summary>///can define constructors, but unlike classes, the default constructor here still exists///</summary> public Str              Uctpositivenumber (int value) {if (value <= 0) {  throw new Exception ();        } this.number = value; }///<summary>///Implement Clone method, return current object///</summary>//&LT;RETURNS&GT;&LT;/RETURNS&G        T        public Object Clone () {return new Structpositivenumber (This.number); }    }

Call

static void Main (string[] args) {//Declaration variable, assignment structpositivenumber pNumber1 = Structpositivenum ber.            InitialValue;            Pnumber1.number = 1;            PNumber1 assigns to pNumber2 structpositivenumber pNumber2 = pNumber1;            Change the value of pNumber2 pnumber2.number = 2; See print results, change the value of PNumber2, but do not affect PNumber1 Console.WriteLine (pnumber1.number);//1 Console.WriteLine (Pnumber            2.Number);//2//Reinitialize PNumber2, change the initial value through constructor generation.            PNumber2 = new Structpositivenumber (3); Console.WriteLine (pnumber2.number);//3//Call clone to copy PNumber2 to PNumber1 pNumber1 = (Structpositivenumbe            R) Pnumber2.clone ();            Console.WriteLine (pnumber1.number);//3//Change the value of PNumber1, but PNumber2 value does not change Pnumber1.number = 4;        Console.WriteLine (Pnumber1.number);//4 Console.WriteLine (Pnumber2.number);//3 console.readline (); }

Results

Then look at the reference type definition:

public class classpositivenumber:icloneable    {        private int number;        public int number        {            get            {                return this.number;            }            Set            {                if (value <= 0)                {                    throw new Exception ();                }                This.number = value;            }        }        The reference type itself can be initialized to null without defining an initial value        //public readonly static Classpositivenumber initialvalue = new Classpositivenumber () ;        public classpositivenumber (int value)        {            if (value <= 0)            {                throw new Exception ();            }            This.number = value;        }        public Object Clone ()        {            return new Classpositivenumber (This.number);        }    }

Call

      static void Main (string[] args)        {            Classpositivenumber cnumber1;//default value is null            cNumber1 = new Classpositivenumber (1);            Classpositivenumber cNumber2 = cNumber1;            Cnumber2.number = 2;            As can be seen, two references to the same object            Console.WriteLine (cnumber1.number);//2            Console.WriteLine (cnumber2.number);//2            //Reinitialize CNumber2, the previous object has been discarded            cNumber2 = new Classpositivenumber (3);            Console.WriteLine (cnumber2.number);//3                        //replication is a copy of an object, so it is two different objects            CNumber1 = (classpositivenumber) Cnumber2.clone ();            Console.WriteLine (cnumber1.number);//3            cnumber1.number = 4;            Console.WriteLine (cnumber1.number);//4            Console.WriteLine (cnumber2.number);//3            console.readline ();        }

Results

By example, you can see that the value type is characterized by the following:
A. Use of struct declaration;
B, cannot inherit class, but can implement interface (of course except object class);
C, value types use value types as fields, but fields cannot have default values;
C, the value type must have a default constructor, and after you define the constructor, the default parameterless constructor still exists. And you can only access the fields in the class, but you cannot access the properties. Symbol = is an assignment for a value type, so an assignment is a value type variable cannot be null, because a value type has no concept of reference, there must be a value.

The above is the basic knowledge of C # collation: basic knowledge (11) value type, reference type of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.