var types in C #

Source: Internet
Author: User

The VAR keyword is a new feature of c#3.0, called inferred type (in fact, the definition of a weakened type).

VAR can replace any type, and the compiler will determine what type you want to use, like object, based on the context, but the efficiency is higher than the object.


We can assign a local variable to infer "type" var instead of an explicit type. The VAR keyword instructs the compiler to infer the type of the variable based on the expression on the right side of the initialization statement. The inferred type can be a built-in type, an anonymous type, a user-defined type, a type defined in a. NET Framework class Library, or any expression.

Example:
Originally defined variables, is to do: data type variable name = value;

Such as:
int a = 1;
String B = "2";

That is, "You must explicitly" specify what data type your variable is in order to assign a value to it. This is important, so remember to compare.

Now in C # 3.0, there is a change, that is, you can not define the variable as above.

Such as:
var a = 1;
The IDE or compiler will "infer that" A is an integer type based on the value you give to a: 1.

Similarly:
var B = "2";

Because the value given to B is a string such as "2", so B is the string type ...

Ps. You can use Var when you are unsure of what type you will use

  

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.

var types in 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.