Implicitly Typed Local Variables
Implicitly Typed Local Variables
It happens time and time again: I’ll be at a game jam, mentoring students, or just showing a friend some Unity C# code, and I’ll type something like this:
var controller = GetComponent<CharacterController>(); |
They’ll go, “whoa wait, isn’t var a JavaScript thing?”
Well the answer is yes… and no, the keyword var exists in both Unity’s C# and JavaScript languages, but they actually mean different things. In C#, it means I’m defining an implicitly typed local variable.
Implicitly Typed Local Variables
When you use var on a local variable in C#, it means that the compiler will attempt to infer the variable’s type based on context. This differs from a dynamic variable in that it will be fast and strictly-typed as if you’d defined the type yourself.
To explain better, consider the following two lines of code:
var controller = GetComponent<CharacterController>();CharacterController controller = GetComponent<CharacterController>(); |
Despite which of these two lines of code you use, Unity will compile them identically. One is not faster or slower than the other. Personally, I really like var for this purpose, because I don’t really like having to type long-winded names like “CharacterController” twice to define a single variable.
If you’re a fan of MonoDevelop or Visual Studio’s code hinting, you’ll be happy to know that using the varkeyword will not cause it trouble, it will still give you correct code hints on the fly as you type.
Thoughts on Usage
Some coders refuse to use implicit typing completely, as it can sometimes be unclear to other readers of the code what type a variable actually is. So I’ll suggest a simple guideline I use: only use implicit typing when the type of the variable is obvious in context. For example:
//This is okay, it is obvious here that the type is "Movement Controller"var moveController = GetComponent<MovementController>();//Less okay, not necessarily obvious what this function is returningvar properties = moveController.GetProperties();//Unless it is obvious, this is probably a better approachMoveProperties properties = moveController.GetProperties();//This I am actually okay with, "targets" is defined right here in plain sightGameObject[] targets = GameObject.FindGameObjectsWithTag("Enemy");var firstTarget = targets[0]; |
You don’t have to follow this rule, but I think it is fair. At least you’ll now get to know the joy of telling somebody “actually, this is a feature of C#!” when they incredulously ask you why you are using a JavaScript keyword.
Also finally, keep in mind that member variables cannot be implicitly typed, so for example:
using UnityEngine;using System.Collections.Generic;public class Player : MonoBehaviour{ //This is a member variable, so you can't use "var" here List<Transform> targets = new List<Transform>(); void Update() { //You can only use them for local vars, like this! var firstTarget = targets[0]; //Or even as iterator variables foreach (var target in targets) { } }} |
Hope you enjoyed this article. If you have any questions or feedback, leave a comment below!
Implicitly Typed Local Variables的更多相关文章
- Effective Java 45 Minimize the scope of local variables
Principle The most powerful technique for minimizing the scope of a local variable is to declare it ...
- Results from queries can be retrieved into local variables
w将查询结果赋值给本地变量. http://dev.mysql.com/doc/refman/5.7/en/stored-program-variables.html Results from que ...
- 【java】A local class access to local variables
内部类参考 A local class has access to local variables. However, a local class can only access local vari ...
- 栈帧的内部结构--局部变量表(Local Variables)
每个栈帧中包含: 局部变量表(Local Variables) 操作数栈(Opreand Stack) 或表达式栈 动态链接 (Dynamic Linking) (或指向运行时常量的方法引用) 动态返 ...
- This inspection warns about local variables referenced before assignment.
关于 local variable 'has' referenced before assignment 问题 今天在django开发时,访问页面总是出现错误提示“local variable 'ha ...
- QIBO CMS /inc/common.inc.php Local Variables Overriding Vul In $_FILES
目录 . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 齐博在/inc/common.inc.php使用$$_key=$value.ext ...
- MyBatis java and MySql local variables
<insert id="create" parameterType="models.entities.CategoryEntity"> set @c ...
- NDK: unable to watch local variables after using GCC4.8
the problem definitly apears after changing toolchain from gcc 4.6 to gcc 4.8. here's a solution wit ...
- 为何 Delphi的 Local Variables 突然没有值显示了
可能是上次编译后 code未再修改过. 试试 随便 输入一个空格,然后F9
随机推荐
- [javascript|基本概念|Unll]学习笔记
Uull类型的值:null(只有一个)|空对象指针|typeof操作符返回object 作用:一般用于对即将保存对象但不知具体对象的引用 特殊:null == undefined --> tru ...
- C# 中有关 using 关键字
关于 C# 中的 using 关键字 我们往往只在代码的开头使用 using 关键字来引入名称空间,这是 using 的一个最常见的使用. 但是,using 关键字是否只有这么一处用武之地吗? 下面, ...
- SQL允许远程访问
1.打开sqlserver对象资源管理器 右键 方面 常规 服务器配置 RemoteAccessEnabled true RemoteDacEnabled true 2.打开SQL SERVER管理 ...
- hbase meta表的结构
下面看下hbase:meta 表的结构,hbase:meta表中,保存了每个表的region地址,还有一些其他信息,例如region的名字,HRegionInfo,服务器的信息.hbase:meta表 ...
- jQuery WIN 7透明弹出层效果
jQuery WIN 7透明弹出层效果,点击可以弹出一个透明层的jquery特效,插件可以调弹出框的宽度和高度,很不错的一个弹出层插件. 适用浏览器:IE8.360.FireFox.Chrome.Sa ...
- JS定时器实例解析
在javascritp中,有两个关于定时器的专用函数. 分别为:1.倒计定时器:timename=setTimeout("function();",delaytime);2.循环定 ...
- PHP操作MongoDB简明教程(转)
转自:http://blog.sina.com.cn/s/blog_6324c2380100ux2m.html MongoDB是最近比较流行的NoSQL数据库,网络上关于PHP操作MongoDB的资料 ...
- Oracle 动态视图6 V$PROCESS
一.视图包含当前系统oracle运行的所有进程信息.常用于将session与进程(oracle进程,操作系统进程)之间建立联系. Column Datatype Description ADDR RA ...
- 测试使用Windows Live Writer
目前是在win7系统下面使用的,曾经在winxp下去配置,却失败了,难道不支持xp? Windows Live Writer好像不支持代码关键字高亮显示啊. int main(void) { prin ...
- with check option(视图 )
建立视图的时候使用WITH CHECK OPTION 与不使用的区别 WITH CHECK OPTION insert update delete 使用with check option 保证ins ...