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

    // // AppDelegate.m // UI1_UIButton // // Created by zhangxueming on 15/6/30. // Copyright (c) 2015年 ...

  2. web前端的十种jquery特效及源码下载

    1.纯CSS3实现自定义Tooltip边框 涂鸦风格 这是一款用纯CSS3打造的自定义Tooltip边框的应用,之前我们讨论过如何用CSS3来实现不同样式的Tooltip,今天的这款Tooltip却可 ...

  3. Ajax 技术一

    一.Ajax概述 1.历史起源 1998年,微软公司Outlook Web Access研发小组在当时的IE浏览器中集成了一种技术,可以在客户端无刷新的前提下向服务器端发送Http请求,这门技术称之为 ...

  4. C++学习——类的继承

    公有继承(public).私有继承(private).保护继承(protected)是常用的三种继承方式. 1. 公有继承(public) 公有继承的特点是基类的公有成员和保护成员作为派生类的成员时, ...

  5. C# http下载(支持断点续传)

    分享下项目里面自己封装的一个http下载类 功能如下: 1.支持断点续传 2.下载失败自动重试 3.超时等异常处理 using System; using System.Collections.Gen ...

  6. jquery.js有红叉

    使用Eclipse 3.7及以上版本时,工程中加入jquery.min.js文件,发现该文件出现错误提示(红×),但使用Eclipse 3.7以前的版本就不会出现这种提示.是因为Eclipse 3.7 ...

  7. ArcGIS API for JavaScript介绍

    ArcGIS API for JavaScript中的类是按照模块组织的,主要包含esri.esri/geometry.esri/renderers.esri/symbols.esri/symbols ...

  8. 基于ArcGIS API for JavaScript的统计图表实现

    感谢原作者分享:https://github.com/shevchenhe/ChartLayer,在使用的过程中,需要自己进行调试修改,主要还是_draw函数,不同的ArcGIS JS API函数有差 ...

  9. vim配置python开发环境

    vim配置python开发环境 一.安装vim sudo apt-get install vim 二.vim基础配置 #Centos6.5 /usr/share/vim/vim72 vi /etc/v ...

  10. phpcms v9 源码解析(3)pc_base::creat_app()

    69     return self::load_sys_classs('application');          在前面我们已经知道了,这个load_sys_classs 静态方法,它加载了P ...