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 returning var properties = moveController.GetProperties(); //Unless it is obvious, this is probably a better approach MoveProperties properties = moveController.GetProperties(); //This I am actually okay with, "targets" is defined right here in plain sight GameObject[] 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
随机推荐
- WCF之错误和异常
CLR异常无法跨越服务边界,所有的异常都被封装(序列化)为SOAP Fault,可以让所有平台的用户接收到. SOAP1.1只有Body.1.2中含有Header+Body. 未捕获异常 异常会从逻辑 ...
- Socket 广播
1.广播端口 Socket中的广播端口是什么意思,是谁对应谁的? 这个广播端口 指定 客户端接收广播消息时要使用的端口号. 参考: 1.快速Python 原型 2.receive UDP broadc ...
- 关闭MyEclipse代码编辑器(breadcrumb)工具条
1. 在工具栏上找“Toggle Breadcrumb”按钮,单击使其恢复未选中状态即可 2. 如果找不到这个按钮.通过菜单“Window->Customize Perspective”打开对话 ...
- Mysql多表查询(两张独立表,一张关系表)
一.数据库设计 1.三个数据表长这样 其中user表记录用户信息,cat主要记录男女性别,mete表是用户id和性别id的对应关系 2.具体数据如下 二.查询目标 查询出所有性别为“男”的 ...
- IIS目录下文件共享后System.IO.File.Exists返回false
场景:在iis目录下,因为特殊需要共享一个文件夹,给到其他的技术人员访问,突然发现小小的操作,搞“大”了,使用 string path = Server.MapPath("~/file/te ...
- ASP.ENT Core Linux 下 为 donet创建守护进程(转载)
原文地址:http://www.cnblogs.com/savorboard/p/dotnetcore-supervisor.html 前言 在上篇文章中介绍了如何在 Docker 容器中部署我们的 ...
- 一个PHP加密脚本,达到一定免杀效果
<?php /**************************************** *author: L.N. *blog : [url]http://lanu.sinaapp.co ...
- (转)android底部弹出iOS7风格对话选项框(QQ对话框)--第三方开源--IOS_Dialog_Library
本文转载于:http://blog.csdn.net/zhangphil/article/details/44940339 完成这个效果的是使用了 IOS_Dialog_Library 下载地址:ht ...
- sqlserver中distinct的用法(不重复的记录)
下面先来看看例子: table表 字段1 字段2 id name 1 a 2 b 3 c 4 ...
- Android设置背景图像重复【整理自网络】
1:在res/drawable文件下新建一个xml文件tool_bar_bg_repeat.xml比如为: <?xml version="1.0" encoding=&quo ...