C # What does 3.0 bring to us (4) -- var, a local variable with implicit type

Source: Internet
Author: User

In C #3.0, allow us to define variables like this
VaR age = 10;
VaR name = "James ";
VaR time = datetime. now;
VaR books = new string [] {"AA", "BB "};
But that's all. var only allows us to define the C # compiler to deduce the type of variables through context.
VaR X; // error. There is no initialization device to deduce the type.
Var y = {1, 2, 3}; // error. The set initializer is not allowed.
VaR z = NULL; // error. The null type is not allowed.
This is not allowed.
VaR A = 10;
A = "James ";
Let's look at the Il Implementation of the privacy type.
C #2.0
. Method public hidebysig instance void oldvar () cel managed
{
// Code size 8 (0x8)
. Maxstack 1
. Locals Init ([0] string name)
Il_0000: NOP
Il_0001: ldstr "James"
Il_0006: stloc.0
Il_0007: Ret
} // End of method testvar: oldvar
C #3.0
. Method public hidebysig instance void newvar () cel managed
{
// Code size 8 (0x8)
. Maxstack 1
. Locals Init ([0] string name)
Il_0000: NOP
Il_0001: ldstr "James"
Il_0006: stloc.0
Il_0007: Ret
} // End of method testvar: newvar
Exactly the same.

I guess the emergence of VaR actually exists completely in combination with the anonymous type.

VaR A = new {name = "James", age = 25 };
Console. writeline (A. Name );
Console. writeline (A. Age );

There are also many applications in LINQ.

Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
VaR querylownums =
From num in numbers
Where num <5
Select num;
Foreach (VAR s in querylownums)
{
Console. Write (S. tostring () + "");
}

That is to say, when the object type is anonymous or the object type is unpredictable.
Code such as VAR age = 10; it is better to write less. First, it is type security, and then it causes as few obstacles as possible for code reading.

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.