Description of the var keyword in C # C #

Source: Internet
Author: User

var is a 3.5 new definition of the type of the variable is actually the weakening type of the definition of Var can be substituted for any type of compiler will be based on the context to determine what type you want to use in the case of Var I think you can not be sure what type you will use var similar Object but efficiency is higher than object.

Or in layman's words:

var can be understood as an anonymous type, and we can think of it as a placeholder for declaring a variable. It is primarily used when declaring a variable, when the data type cannot be determined.

The following four characteristics are used when defining variables with Var:

1. Must be initialized at the time of definition. It must be var s = "ABCD" form, not the following form: Var s; s = "ABCD";

2. Once initialization is complete, it is not possible to assign a value that differs from the initialization value type.

3. The var requirement is a local variable.

4. Using var to define variables is different from object, which is exactly the same as defining variables in terms of efficiency and using strongly typed methods.

Instance:

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.Threading.Tasks;Namespacefirstpriject{Classprogram {Staticvoid Main (String[] args) {//Declaring and initializing variablesvar name ="Tom";var age =10var sex = true// Gets the data type of the variable, t_name = Name. GetType (); Type t_age = age. GetType (); Type t_sex = Sex. GetType (); // print results Console.WriteLine (  " "// do not automatically close the console, wait for input  

Example result diagram:

Description of the var keyword in C # C #

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.