From C ++ to C #: What changes do we need to pay attention?

Source: Internet
Author: User

Abstract: C # is based on the syntax and semantics of C ++. It facilitates C language programmers to use the. NET and general language runtime libraries. Although switching from C ++ to C # is relatively easy, there are still some points worth noting. In this article, we will explore some new features, such as fragment collection, attributes, foreach-loop loops, and interfaces.

Every 10 years or so, programmers need to spend a lot of time and energy learning new programming technologies. In 1980s, it was Unix and C, and in 1990s it was Windows and C ++. Now it has reached Microsoft's. NETFramework and C #. Although new technologies need to be learned, the benefits are far higher than the labor cost. Fortunately, the analysis and design of most projects using C # And. NET have no essential changes in C ++ and Windows. In this article, I will introduce how to make a leap from C ++ to C.

Many articles have already introduced C #'s improvements to C ++, so I will not repeat these questions here. Here, I will focus on the biggest change from C ++ to C #: the change from an unmanageable environment to a manageable environment. In addition, I will make some mistakes that C # programmers can easily make for your reference. In addition, I will explain some new functions that C # can affect programming.

Turn to manageable Environments

C ++ is designed to be a low-level, platform-independent object-oriented programming language. C # is an advanced component-oriented programming language. The transformation to a manageable environment means a major shift in thinking about programming. C # no longer deals with subtle control, but lets the architecture help you deal with these important issues. For example, in C ++, we can use new to create an object at a specific position in the stack, heap, or even memory.

In the. NET manageable environment, we no longer need to perform that subtle control. After selecting the type to be created, its location is fixed. Objects of simple types (ints, double, and long) are always created in the stack (unless they are included in other objects), and classes are always created in the heap. We cannot control the location where the object is created in the heap, nor can we obtain this address. We cannot place the object in a specific location in the memory. (Of course, there are ways to break through these limitations, but that is an alternative method .) We can no longer control the object's lifecycle. C # does not have a destructor. The fragment collector recycles the memory occupied by the object, but this is non-explicit.

It is exactly this structure of C # that reflects its infrastructure. There are no multiple inheritance and templates, because in a manageable fragment collection environment, multi-inheritance is difficult to implement efficiently.

The simple type in C # is only a simple ing of the types in the Universal Language Runtime Library (CLR). For example, the int in C # Is a System ing of System. Int32. The data type in C # is determined not by the language, but by the CLR. In fact, if you still want to use the objects created in Visual Basic in C #, you must make your programming habits more in line with CLR rules.

On the other hand, manageable environments and CLR also bring us benefits. Except for fragment collection and all. in addition to the Unified Data Types in the. NET language, it also provides us with a powerful component-oriented programming language, without the need to provide special support for later binding, type discovery and later binding are both built into the language. Attribute is a member of the first class in C # language, and the event and proxy are also.

The main advantage of a manageable environment is. NETFramework. Although this framework can be used in all. NET languages, C # can better use the rich classes, interfaces, and objects in the. NET Framework.

Traps

C # looks very similar to C ++, which makes it easier for us to switch from C ++ to C #, but there are also some errors. The code written in C ++ is very beautiful. in C #, compilation may fail, and unexpected results may even occur. The syntax of C # And C ++ does not change much. The compiler can find most of the differences between the two. I will not pay much attention here, here I will introduce several important changes that are prone to problems:

Reference Type and Value Type

In C #, the value type and reference type data are different. Simple data types (int, long, double, etc.) and structures belong to value type data, and classes and objects belong to reference type data. Unless included in a reference type variable, the value of the value type variable is stored in the stack, just like in C ++. Variables of the reference type are also stored in the stack, but their values are the addresses of objects stored in the stack, which is similar to C ++. A value type variable is used to pass its own value to the method, and a reference type variable is used to pass its own pointer to the method.

Structure

The structure in C # differs significantly from that in C ++. In C ++, the structure is more like a class. Apart from default inheritance, the default access permission is public rather than private. In C #, the structure is completely different from the class. It is used to encapsulate lightweight objects. It is a value-type data type and transmits the value of a variable rather than its address during transmission. In addition, they have some limitations that do not apply to classes. For example, they cannot be inherited, and they do not have any basic classes except System. ValueType. The structure cannot define a default constructor.

On the other hand, because the structure is more efficient than the class, it is very suitable for creating lightweight objects. Therefore, if its disadvantages do not affect your software, the use structure is much more efficient than the use of classes, especially for small objects.

Everything is an object

In C #, everything is obtained by inheriting the Object, including the created class and int, structs equivalent type variables. The Object class provides some useful methods, such as ToString. An example of using ToString is used with System. Console. WriteLine. It can accept a string and many objects. Unlike the printf statement, to use WriteLine, you must provide replacement variables. Assume that myEmployee is an instance of the User-Defined Employee class, And myCounter is an instance of the User-Defined Counter class:

Console. WriteLine ("Theemployee: {0}, thecountervalue: {1 }",
MyEmployee, myCounter );


The WriteLine calls the Object. ToString method of each Object and replaces the variable returned as a parameter. If the Employee class does not overwrite the ToString, the default implementation will be called (inherited by System. Object), and the class name will be returned as a string. Counter will overwrite ToString and return an integer variable. Therefore, the output of the above Code is:

Theemployee: Employee, thecountervalue: 12


What happens if I pass an integer variable to WriteLine? Because ToString cannot be called for integer variables, the compiler will automatically encapsulate the integer variables in an object instance. When WriteLine calls ToString, the object returns a string that represents the integer variable value. The following code illustrates the problem:

Class usage

UsingSystem;
// Do not overwrite the ToString class
PublicclassEmployee
{
}
// Overwrite the ToString class
PublicclassCounter
{
PrivateinttheVal;
PublicCounter (inttheVal)
{
This. theVal = theVal;
}
PublicoverridestringToString ()
{
Console. WriteLine ("CallingCounter. ToString ()");
ReturntheVal. ToString ();
}
}
PublicclassTester
{
PublicstaticvoidMain ()
{
// Create a class instance
Testert = newTester ();
// Call non-static members
// (Mustbethroughaninstance)
T. Run ();
}
// Demonstrate the non-static method for calling ToString
PublicvoidRun ()
{
EmployeemyEmployee = newEmployee ();
CountermyCounter = newCounter (12 );
Console. WriteLine ("Theemployee: {0}, thecountervalue: {1 }",
MyEmployee, myCounter );
IntmyInt = 5;
Console. WriteLine ("Herearetwointegers: {0} and {1}", 17, myInt );
}
}


Reference parameters and Output Parameters

Same as in C ++, the method in C # can only have one return value. In C ++, we have overcome this restriction by using pointers or indexes as parameters. When the called method changes the parameters, a new value can be obtained by calling the method.

When you pass an index as a parameter to the method, you can only access the original object strictly in the way provided by the passing index or pointer. This method cannot be used for value type variables. If you want to pass a value variable through a reference parameter, you need to add the ref parameter before it. As follows:

PublicvoidGetStats (refintage, refintID, refintyearsServed)


Note that you must use the ref parameter in the method definition and the ref parameter in the actual call to the method.

Fred. GetStats (refage, refID, refyearsServed );


Now, we can define the age, ID, and yearsServed variables in the call method, and pass them to GetStats to get the changed value.

C # requires a clear value assignment. That is to say, before calling the GetStats method, you must initialize the three local variables age, ID, and yearsServed. This seems redundant, because we only use them to get new variable values from GetStats. To solve this problem, C # provides the out key, indicating that we can pass out-of-initialization variables to the method. These variables will be passed by referencing the variables:

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.