• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
14
Question by instruct9r · Oct 24, 2015 at 11:35 AM · variablevardeclarationtypeof

Why woud i use var in C# ?

Hello..

I've been usind C# for quite some time and i am usually defining my variables with their type.

Anyway i have recently watched some tutorials and the person, that explains them is using "var" to declare variables. Why is that? Is it good for some reason or it's just a way to define a variable that you don't know the type of, at the time of declaration? If so, does Unity re-declare it, when it knows the type? Coud that bring some errors...

For example t$$anonymous$$s piece of code:

 var vertColors = new Color[mesh.vertexCount];
 
         for (var i = 0; i < mesh.vertexCount; i++)
         {
             vertColors[i] = color;
         }
 
         mesh.colors = vertColors;
         mesh.RecalculateNormals();

Why using var for declaring "vertColors"? And why isn't Unity expecting to have "var[]" for declaring an array?

The first line can be also written like t$$anonymous$$s:

 Color[] vertColors = new Color[mesh.vertexCount];

but here Unity expects me to write [], after the type of the variable. Why it doesn't give error, on the declaration (with var) above??

The tutor is also isung it to declare the "i" for the loop.. I don't get that at all...

So it seems that i can declare every type with var, instead of the type. Is that more expensive, than declaring the exact type?

As a whole, why woud i use var...

Thanks :)

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image bubzy · Oct 24, 2015 at 11:41 AM 0
Share

the compiler likely works it out for you and adds the bit you left out when you use var i personally find that declaring the type in the first instance leads to much more readable code.

just my opinion tho

1 Reply

· Add your reply
  • Sort: 
avatar image
29
Best Answer

Answer by Bunny83 · Oct 24, 2015 at 12:24 PM

The var keyword still declares a typed variable and it only works when you immediately assign a value to to variable. It also only works for local variables in C#. So only inside methods and not for class variables. It has no advantanges and is just a shorter way to declare a local variable.

Since you have to assign a concrete type when the variable is created it's usually clear what type it has.

Example:

 var list = new List<GameObject>();

It's especially handy for long generic type names:

 var dict = new Dictionary<string, List<GameObject>>();
 // it's equal to:
 Dictionary<string, List<GameObject>> dict = new Dictionary<string, List<GameObject>>();

You should avoid using it where the type can't be "seen" directly. Like:

 List<MyCustomClass> SomeMethod()
 {
     // ...
 }
 
 void Start()
 {
     var list = SomeMethod(); // bad example, but also works.
 }

In a lot IDEs (like Visual Studio) you can hover over the "var" keyword and it shows a popup with the inferred type.

edit
About the Color array. Color[] is a completely different type than Color. Adding square brackets to a type defines a new type. An array type with the given element type. "var" just replaces any type, no matter w$$anonymous$$ch type. Again it's just syntactical sugar. There's absolutely no difference in the compiled code whether you use "var" or not.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image instruct9r · Oct 24, 2015 at 12:31 PM 0
Share

Nice.. Thanks for the explanation :)

avatar image Bunny83 · Oct 24, 2015 at 12:43 PM 2
Share

ps: I usually don't use or recommend to use "var" in a for loop since the actual type depends on the initial value. Also since "int" is the most common type i don't see any good reason to use var over int. It might make sense when iterating through a linkedlist node like that:

 LinkedList<SomeType> list;
 for(var n = list.first; n != null; n = n.Next)
avatar image instruct9r Bunny83 · Oct 24, 2015 at 03:25 PM 3
Share

Honestly i don't intend to use "var" at all, since (At least in my opinion), declaring the variable with the exact type is looking better, when reviewing / updating the code later...

Thanks again, for the nice explanation :)

cheers

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

30 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Adding to variable only once? 0 Answers

Assigning variables depending on other variables 1 Answer

Assign GameObject OnMouseUp not through inspector -2D 1 Answer

Variable not assigned but is. 0 Answers

how to controll a variable of a script from another script 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges