Inferred type var

Source: Internet
Author: User

1. Why use inferred type var

var can automatically infer the local variable type based on the initial value of the variable, and can use Var when it is not possible to determine the specific type of the variable used

2. How to use inferred type var

Client code

        Static voidMain (string[] args) {            varA =Ten; varClassName ="Learning from Var"; //var student = new Student{studentname = "Wang Hua", age = +};//Creating Objects            varStudent =New{Studentname ="Simon", age = -};//Anonymous ClassConsole.WriteLine ("{0} personally in {1}, where {2}, {3} years old, mastered the best! ", A, className, student. Studentname, student.            Age);        Console.ReadLine (); }

Sudent class definition

     Public class Student    {        publicstringgetset;}          Public int Get Set ;}          Public int Get Set ;}    }

Output

This shows that Var can infer the type of a variable based on the value of the variable

Note: Anonymous classes: Anonymous classes do not need to write classes and their members in advance, and only add properties cannot add methods, anonymous classes are not nameless, but the compiler generates class names in the background

3. Questions to note when using inferred type var

(1) variables using var must be local variables, member variables cannot be modified with Var

(2) When using VAR, the variable must be initialized at the same time and cannot be empty

(3) var itself does not define a new type

4. The difference between Var and object

var is similar to object, but there are some differences in that Var cannot be assigned another type of assignment after inferring the type of the variable, and object does not have this limitation

        Static void Main (string[] args)        {            objectten;             " should be right. " ;             var Ten ;             " Are you wrong? ";        }

The former a compile no problem, the latter B has a problem, so you can see the difference between Var and object

Inferred type var

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.