C # New keyword and object type conversion (double parenthesis, is operator, as operator)

Source: Internet
Author: User

First, the New keyword

The CLR requires all objects to be created through new, with the following code:

Object obj=New object ();

Here's what the new operator does.

1. The number of bytes required for all instance fields defined in the calculation type and all of its base types (until System.Object, although it does not define its own instance field). Each object on the heap requires some extra members, including the type object pointer and the synchronous index block. The CLR uses these members to manage objects. The number of bytes for the extra member is counted in the size of the object.

2. Allocates the memory of the object by allocating the required number of bytes from the managed heap, and all bytes allocated are set to 0

3. Initialize the object's "type Object pointer" and "Synchronize index block" members

4. Invokes the instance constructor of the type, passing the arguments specified in the new call, and most compilers automatically generate code in the constructor to call the base class constructor, each of which is responsible for initializing the instance fields of the type definition. Finally call the System.Object constructor, The constructor does nothing.

Note: There is no delete operator corresponding to the new operator, in other words, there is no way to display the freed memory allocated for the object. The CLR uses a garbage collection mechanism to automatically detect that an object is not being used or accessed and automatically frees the object's memory.

Second, object type conversion

1. Basic knowledge

One of the most important features of the CLR is type safety. At run time, the CLR always knows what type the current object is, and calls the GetType method to know what type the current object is, since Gettpye is a non-virtual method, So a type cannot be disguised as another type. For example, the employee type cannot override the GetType method to return a superhero type.

However, in daily development, it is often necessary to convert one type to another, and the CLR allows the object to be converted to its actual type or to any of its base types. Each programming language specifies how the developer specifically makes this transition. C # does not require any special syntax to convert an object to its base type. Conversion to a base type is considered a type-safe conversion.

The code for converting an object into a base type is as follows:

     Public class program    {        staticvoid Main (string[] args)        {            //  Because object is the base class for all types in the CLR, you do not need to transform the            new person ();        }    }     Internal class Person {}

However, when converting an object to its derived type (that is, subtype), C # requires an explicit conversion because the conversion might fail at run time!

To convert an object to its derived type (subtype), the code is as follows:

     Public class program    {        staticvoid Main (string[] args)        {            //  Because object is the base class for all types in the CLR, you do not need to transform the            new person ();             // A cast is required because person derives from Object            Person p = (person) obj;        }    }     Internal class Person {}

Note: The object to be cast must be a derived type of the receive type, and if not, the compiler will report an System.InvalidCastException exception.

2. Use is and as as to cast

(1), is operator

Another way to type conversion in C # is to use the IS operator, is to check whether the object is compatible with the specified type, to return a Boolean value of TRUE or FALSE, note that the IS operator never throws an exception, and the code is as follows:

     Public class program    {        staticvoid Main (string[] args)        {            new  Object ();              is Person );             New Person ();              is Person );            Console.readkey ();        }    }     Internal class Person {}  

The IS operator is typically used as follows:

if  is Person ) {    = (person) Stu;}

In the code above, the CLR actually performed two code checks, the IS operator first verifies that Stu is compatible with the person type, and if so, theCLR verifies again whether Stu refers to a person type when it is internally transformed. The CLR's type checking enhances security, but undoubtedly has a certain impact on performance, and should be that the CLR must first determine the actual type of the variable reference and use each base type to check the specified type.

2, as operator

To simplify the operation of the IS operator while providing the performance of the Is operator, C # specifically provides the as operator, and the as operator works in the same way as coercion type conversions, except that it never throws an exception, and if the object cannot be converted, The result is null. So the correct use of the AS operator is to check if the transformation result is null, and if the result is directly used, the System.NullReferenceException exception may be thrown, the code is as follows:

     Public classProgram {Static voidMain (string[] args) {Object obj=NewObject (); Person P= obj asperson;//This conversion will fail, but P will be set to null without throwing an exception            stringExceptioninfo = P.tostring ();//Access P here will throw an exceptionConsole.WriteLine (Exceptioninfo);        Console.readkey (); }    }    Internal classPerson {}

C # New keyword and object type conversion (double parenthesis, is operator, as operator)

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.