CSharp - Type Inference and usage of var

/*

Author: Jiangong SUN

*/


Type Inference a concept of CSharp 3 that is used with keyword var, which lets the compiler decide the object type.

It's mainly used with anonymous types and LINQ when you manipulate different types of data like XML, SQL, Entities and Objects.


If you have to treat some data which is used only once, and in a local scope, you don't have to create a new type for it. You can just use anonymous type. In case of modification, you just need to modify your data directly.

For example:

 var belle = new {Name = "Belle", Age = "15", Sex = "Female"};

As to the usage of data source, you just need to handle part of the data type in most cases. And this can reduce the network traffic and server charges.

For example:

var ienums = from c in customers
             select new { Name = c.CustomerFirstName, Id = c.CustomerId };
In more complicated cases, it's not recommended to use Explicit types than anonymous types too.


Next, I'll talk about the usage of var. 

If you and your collegues can easily understand what type the object is, you can use explicit type or var. 

If you are initializing data with declaration and the type is complicated, it's recommended to use var for preventing bad readability and distraction of attention.

If you are treating data from different data sources and it's used once, you can use var. If it's used widely in an application, you can convert to a specific type.

If you are using anonymous type, you need var.

If you are in other cases, it's recommended to use explicit type.


I hope this post can do help to your daily work! Enjoy coding!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值