C #3.0 _ 2-var

Source: Internet
Author: User
Tags mscorlib
Demo
 
StaticVoidMain () {var num =6; Var STR ="Dancing"; Var Dou =9.25d; Console. writeline (Num); console. writeline (STR); console. writeline (DOU );}

VaR keyword, used to declare and initialize local variables. The compiler deduced the actual type of the Variable Based on the = Statement on the right. Therefore, the requirement for using VAR is that the statements on the right must allow the compiler to deduce the actual type. Therefore, the right side of the = sign must have a value, that is, it must be initialized, not just declared. But some are not easy to read.Code. At the same time, the emergence of another new feature [anonymous type] in C #3.0 gave var a foothold.

VaR does not represent a weak type. The following il code:

 1   . Method   Private  Hidebysig Static Void Main () Cel   Managed  2   {  3     . Entrypoint  4     //  Code size 41 (0x29)  5     . Maxstack    1  6     . Locals  Init ([ 0 ] Int32  Num,  7 [ 1 ] String  STR,  8 [ 2 ] Float64  Dou)  9     Il_0000:    NOP 10     Il_0001:    LDC. i4.6  11     Il_0002:    Stloc.0  12     Il_0003:    Ldstr Bytearray ( 71 4e 1e 82   25   66 CB 79  )  13    Il_0008:    Stloc.1  14     Il_0009:    LDC. R8       9.25  15     Il_0012:    Stloc.2  16     Il_0013:    Ldloc.0  17     Il_0014:    Call         Void [Mscorlib] system. Console: writeline (Int32  )  18     Il_0019:    NOP  19     Il_001a:    Ldloc.1  20     Il_001b:    Call         Void [Mscorlib] system. Console: writeline ( String  )  21     Il_0020:    NOP 22     Il_0021:    Ldloc.2  23     Il_0022:    Call         Void [Mscorlib] system. Console: writeline ( Float64  )  24     Il_0027:    NOP  25     Il_0028:    RET  26 }//  End of method test: Main 

Lines 6-8 show that the compiler has made a correct type inference.

Summary

VaR is a compiler technique and syntactic sugar. The anonymous type must be used with this keyword.

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.