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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 【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 ...

  4. 栈帧的内部结构--局部变量表(Local Variables)

    每个栈帧中包含: 局部变量表(Local Variables) 操作数栈(Opreand Stack) 或表达式栈 动态链接 (Dynamic Linking) (或指向运行时常量的方法引用) 动态返 ...

  5. This inspection warns about local variables referenced before assignment.

    关于 local variable 'has' referenced before assignment 问题 今天在django开发时,访问页面总是出现错误提示“local variable 'ha ...

  6. QIBO CMS /inc/common.inc.php Local Variables Overriding Vul In $_FILES

    目录 . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 齐博在/inc/common.inc.php使用$$_key=$value.ext ...

  7. MyBatis java and MySql local variables

    <insert id="create" parameterType="models.entities.CategoryEntity"> set @c ...

  8. 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 ...

  9. 为何 Delphi的 Local Variables 突然没有值显示了

    可能是上次编译后  code未再修改过. 试试 随便 输入一个空格,然后F9

随机推荐

  1. Grunt 认识

    基本工作流: JS合并.JS压缩.CSS压缩.CSS Sprite.图片优化.测试.静态资源缓存(版本更新)... 基于工作流产生的工具: JSHint(jshint.com).CSSLint(css ...

  2. 8款超酷而实用的CSS3按钮动画

    1.CSS3分享按钮动画特效 这是一款基于CSS3的社会化分享按钮,按钮非常简单,提供了分享到twitter.facebook.youtube等大型社交网站.每一个分享按钮都有个大社交网站的Logo图 ...

  3. Excel中 设置使得每行的颜色不一样

        在编写测试案例的时候,众多的excel行看的眼睛花花的,这里给出一个小技巧,设置Excel的每行显示的颜色不一样,最终的效果如下:    具体操作:     1. Ctrl+A全选所有表格区域 ...

  4. 《Apache之虚拟主机的配置》——RHEL6.3

    1.安装httpd软件包: Yum install httpd 2.启动apache服务: [root@redhat Desktop]# /etc/init.d/httpd start Startin ...

  5. c#配置log4net步骤

    1.引入添加log4net.dll引用 2.建立配置文件Log4Net.config(名字自定义).文件内容参考,输出的文件名称可更改 .运行是要放入到相应bin/debug(release) 目录 ...

  6. linux前景到底怎么样啊?

    我就不长篇大论,举四个例子你看看. 1.目下最热最潮最流行的云计算技术的背后是虚拟化和网格技术,而虚拟化和网格技术基本是Linux的天下,目前虚拟化的三大家:Vmware,Xen,Hyper-V中,市 ...

  7. 开发流程习惯的养成—TFS简单使用

    才开始用,所以是个很基础的介绍,欢迎大家一起交流学习 一.追本溯源 讲到开发流程,还要从敏捷开始,因为敏捷才有了开发流程的重视,整个流程也是按照敏捷的思想进行的,这里不再叙述敏捷的定义 敏捷的流程(个 ...

  8. ES5中的有9个Array方法

    Array.prototype.indexOf Array.prototype.lastIndexOf Array.prototype.every Array.prototype.some Array ...

  9. ios7.0结合storyborad实现页面跳转的总结

    折腾了一整天,本文总结一下ios7.0页面跳转有关的内容 storyboard的潜规则 我接触ios很晚,环境已经是xcode5+ios7,所以对以前的IOS开发模式并不了解.在网上查阅了很多资料,发 ...

  10. Mysql ERROR 1045 (28000): Access denied for user 'root'@'localhost'(using password: YSE)

    安装mysql后,使用命令登录mysql居然报错了,Mysql ERROR 1045 (28000): Access denied for user 'root'@'localhost'(using ...