Infered type in C# -- var -- C#

6 篇文章 0 订阅
2 篇文章 0 订阅

Introduction

An infered type refers the compiler can know the type without explicitly declare type to an identifier. For example, an identifier should be declared like this.

int number = 1;

 However, it can be done with keyword var.

var tf1 = true;

var

Keyword var declares an identifier inferredly. The compiler will distinguish the type it should be according to the initialization. For above example, 

var tf2 = true;

First, according to true (after assignment), the compiler knows that type of tf2 should be a boolean type. Then the tf2 will be initialized with true.

They are equivalent to the above example and the following example.

bool tf2 = true;

Example

Example with Compiler Error

var x;                  // Error, no initializer to infer type from
var y = {1, 2, 3};      // Error, array initializer not permitted
var z = null;           // Error, null does not have a type
var u = x => x + 1;     // Error, anonymous functions do not have a type
var v = v++;            // Error, initializer cannot refer to v itself

The declaration about x is NOT allowed since there are no initialization thus the compiler can not know the type it should be. 

The declaration about y is NOT allowed since initialization about array is NOT allowed.

The declaration about z is NOT allowed since null does NOT have a type thus, again, the compiler can not know the type it should be. 

The declaration about u is NOT allowed since anonymous functions do not have a type thus, again, the compiler can not know the type it should be. 

The declaration about v is NOT allowed since it is NOT allowed that initializer refer to itself. The reason why is that the v has NOT been declared and initialized yet but the compiler try to know the type of v.

Reference

Statements - C# language specification | Microsoft Learn

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值