10 C # errors that C ++ programmers can easily make

Source: Internet
Author: User

We know that the syntax of C # is very similar to that of C ++. The difficulty of the transformation from C ++ to C # lies not in the language itself, but in familiarity.. NET manageable Environment and. NET Framework.

Although the syntax changes of c # And C ++ are very small, they will hardly affect us, but some changes are enough to keep some careless C ++ programmers in mind. In this article, we will discuss the ten mistakes that C ++ programmers are most likely to make.

Trap 1: There is no clear end Method

For most C ++ programmers, the biggest difference between C # And C ++ is fragment collection. This also means that programmers no longer have to worry about memory leaks and ensure that all useless pointers are deleted. But we can no longer precisely control the process of killing useless objects. In fact, there is no clear destructor in C.

If you use non-manageability resources, you must release them explicitly after they are not used. Implicit control over resources is provided by the Finalize method (also known as finalizer). When an object is destroyed, it is called by the fragment collection program to reclaim the resources occupied by the object.

Finalizer should only release non-manageability resources occupied by destroyed objects, and should not involve other objects. If only manageability resources are used in the program, the Finalize method is not required and should not be executed. The Finalize method is only used in the process of non-manageability resources. Because the finalizer occupies a certain amount of resources, you should only execute finalizer in the method that requires it.

Directly calling the Finalize method of an object is absolutely not allowed (unless the Finalize of the basic class is called in the Finalize of the subclass .), The fragment collector automatically calls Finalize.

In terms of syntax, the destructor in C # is very similar to C ++, but they are actually completely different. The destructor in C # is just a shortcut to define the Finalize method. Therefore, the following two pieces of code are different:

~MyClass()

{

// Tasks to be completed

}

MyClass.Finalize()

{

// Tasks to be completed

base.Finalize();

}

Error 2: Who is used by Finalize and Dispose?

From the above discussion, we know that explicit calls to finalizer are not allowed, and it can only be called by the fragment collection program. If you want to release a limited number of non-manageability resources (such as file handles) that are no longer in use as soon as possible, you should use the IDisposable interface, which has a Dispose method, it can help you complete this task. Dispose is a method that can release non-manageability resources without waiting for Finalize to be called.

If the Dispose method is used, the fragment collection program should be prevented from executing the Finalize method on the corresponding object. Therefore, you need to call the Static Method GC. SuppressFinalize and pass the pointer of the corresponding object to it as a parameter. The Finalize method can call the Dispose method. Accordingly, we can get the following code:

publicvoidDispose()

{

// Complete the cleanup operation

// Notify GC not to call the Finalize method again

GC.SuppressFinalize(this);

}

publicoverridevoidFinalize()

{

Dispose();

base.Finalize();

}

For some objects, it is more appropriate to call the Close method (for example, it is more appropriate to call Close for object objects than Dispose ), you can create a Dispose method for the private attribute and a Close method for the public attribute, and call Dispose to call the Close method for some objects.

Dispose is always called, and the execution of finalizer is also uncertain (we cannot control when the GC will run ), C # provides a Using statement to ensure that the Dispose method is called as early as possible. The general method is to define which object to use, and then use parentheses to specify an activity range for these objects. In the case of the innermost parentheses, the Dispose method will be automatically called, process the object.

usingSystem.Drawing;

classTester

{

publicstaticvoidMain()

{

using(FonttheFont=newFont("Arial",10.0f))

{

// Use theFont object

} // The compiler will call Dispose to process theFont objects

FontanotherFont=newFont("Courier",12.0f);

using(anotherFont)

{

// Use the anotherFont object

} // The compiler will call Dispose to process the anotherFont object

}

}

In the first part of this example, the Font object is created in the Using statement. When the Using statement ends, the system calls Dispose to process the Font object. In the second part of this example, the Font object is created outside the Using statement. When you decide to use it, place it in the Using statement. When the Using statement ends, the system will call Dispose.

The Using statement can also prevent other accidents and ensure that the system will call Dispose.

Error 3: The value variables in C # are different from the referenced variables.

Like C ++, C # is also a strong programming language. Data Types in C # are classified into two categories: the data types inherent in C # language and user-defined data types, which are similar to C ++.

In addition, the C # Language divides variables into value type and reference type. Unless it is included in a reference type, the value of the value type variable is kept in the stack, which is very similar to the variable in C ++. The reference type variable is also a type of stack, and its value is the address of the object in the heap, which is very similar to the pointer in C ++. The value of a value type variable is passed directly to the method. When a referenced variable is passed as a parameter to the method, the index is passed.

Class and interface can create reference class variables, but it should be noted that the structure data type is a built-in data type of C # and also a value type.

Error 4: Implicit data type conversion

Boxing and unboxing are two processes used to make the value data type be used as the index data type. A value variable can be encapsulated into an object and then unwrapped back to the value variable. Data Types in C #, including built-in data types, can be implicitly converted into an object. Wrap a value-type variable to generate an object instance, and then copy the variable to the instance.

Boxing is implicit. If a variable of the value data type is used where the index data type is required, the value variable is implicitly converted to the variable of the index data type. Boxing will affect the performance of code execution, so we should avoid it as much as possible, especially when the data volume is large.

To convert a packaged object back to the original value type variable, you must unpackage it explicitly. Two steps are required for unpacking: First, check the object instances to ensure that they are packaged by value variables; second, copy the values in the instances to the value variables. To ensure successful unpacking, the unwrapped object must be the index of the object generated by packing the value of a value-type variable.

usingSystem;

publicclassUnboxingTest

{

publicstaticvoidMain()

{

inti=123;

// Package

objecto=i;

// Unpack (must be explicit)

intj=(int)o;

Console.WriteLine("j:{0}",j);

}

}

If the unwrapped object is invalid or the index of an object of different data types, InvalidCastException will occur.

Error 5: The structure and object are different.

The structure in C ++ is similar to the class. The only difference is that, by default, the structure access permission is public, and its inherited permission is public. Some C ++ programmers use structures as data objects, but this is only a convention, not a necessity.

In C #, the structure is only a user-defined data type and cannot replace classes. Although the structure also supports attributes, methods, fields, and operators, inheritance and destructor are not supported.

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.