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. 【转载】#274 - Can't Overload if Methods Differ Only by ref and out Modifiers

    You can overload a method in a class, i.e. define two methods with the same name, if the methods hav ...

  2. Java中注解Annotation的定义、使用、解析

    此例子,用于说明如何在Java中对“注解 Annotation”的定义.使用和解析的操作.注解一般用于自定义开发框架中,至于为什么使用,此处不作过多说明,这里只说明如何使用,以作备记.下面例子已测试, ...

  3. java检测端口号是否配占用

    java检测端口号是否被占用的工具类:       package com.frank.util; import java.io.IOException; import java.net.InetAd ...

  4. 济南学习 Day 3 T3 pm

    仙人掌(cactus)Time Limit:1000ms Memory Limit:64MB题目描述LYK 在冲刺清华集训(THUSC) !于是它开始研究仙人掌,它想来和你一起分享它最近研究的结果. ...

  5. android:layout_weight越大所占比例越大和越大所占比例越小的两个例子

    摘要: 我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3907146.html,享受整齐的排版.有效的链接.正确的代码缩进.更好的 ...

  6. Qt for Android 程序禁止屏幕旋转

    有时候我们希望让一个程序的界面始终保持在一个方向,不随手机(平板)方向旋转而变化:在AndroidManifest.xml的每一个需要禁止转向的Activity配置中加入 android:screen ...

  7. 阿里云服务器 ECS Ubuntu系统安装配置

    1. 登陆服务器 系统开通成功后手机会收到阿里云发来的短信,包含公网IP及root登录密码. WEB管理后台方式 可通过阿里云管理后台选择“连接管理终端…”进行登录 提示输入VNC密码 登录成功后显示 ...

  8. 基础学习总结(八)--Intent中显示意图和隐式意图的用法

    Intent(意图)主要是解决Android应用的各项组件之间的通讯.Intent负责对应用中一次操作的动作.动作涉及数据.附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组 ...

  9. win7局域网无法ping通本机的问题解决方法

    对于window7系统,很多朋友会发现:默认下是不允许被ping的,其实都系统自带的防护墙所阻止了,新建一个策略就可以实现被ping通,如下操作

  10. 封装getElementsByClassName

    function getElementsByClassName(oEle,sClass,sEle){ if(oEle.getElementsByClassName){ return oEle.getE ...