A galaxy var, var away

My current project has me writing C# scripts in Unity. Cool. I haven’t written C# for more than a decade. Today I was reviewing code, and noticed this line:

foreach (var child in Children)

Nothing too exciting. Readable. Easy to understand. But as I took a second look, I realized I didn’t truly know what var is all about. Is it defining a variable? What’s the type of child? Could var be replaced with ChildType? What’s best practice? Should I be using var?

Var was introduced in C# v3.0 circa 2007. It turns out it’s the equivalent to auto in C++, which I wrote about not long ago. Var allows the compiler to determine the type automatically.

So, var defines a variable. The type of var is the type that the compiler deduces. Var could be replaced with the actual type, but best practice is to use var whenever you can, just like auto. I’ll be using it regularly from now on.

Var out.

This entry was posted in CSharp, Game Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s