C # implicit type

Source: Internet
Author: User

Implicit type

(1) Origin

Before an implicit type occurs,

When we declare a variable,

Always specify its type for a variable

Even when foreach is a set,

You must also specify the variable type for the elements of the traversal set.

Implicit type,

Programmers don't have to do this anymore.

(2) Usage

Let's look at the following code:

Var a = 1; // int a = 1; var B = "123"; // string B = "123"; var myObj = new MyObj (); // MyObj myObj = new MyObj ()

The above lines of code play the same role as the comments behind each line of code.

That is to say, when declaring a variable (and assigning values to it at the same time), you do not need to specify the type of the variable. As long as a var is used, the problem is solved.

(3) Are you worried that such writing will reduce performance?

I can tell you responsibly that this write will not affect performance!

The above code and the code in the comments are exactly the same after the compiled IL code (intermediate language code)

(The IL code generated by the compiler based on the variable value and the type of the variable)

(4) benefits of this keyword:

You do not need to write the variable type twice when declaring a variable and assigning values to the variable.

(This really saves developers a lot of time)

When foreach is a set, you can use the var keyword to replace the type of the circular variable.

(5) Considerations

You cannot declare a variable with the var keyword without assigning a value to it.

The compiler cannot export the type of your variable.

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.