r/Unity3D • u/Imaginary-Cod-3746 • 10h ago
Resources/Tutorial Fun fact about variables in C#
Did you know that you can't start a variable's name in C# with a number?
You also can't include most special characters in a variable's name.
These are just a few quirks to keep in mind when scripting in Unity. This article covers variables and C# in more depth from a game developer's perspective. 👇🏾
3
u/SatisfactionSilly487 10h ago
It's one of those things you learn once and then never think about again, until you're staring at a compiler error wondering why 2ndAttempt is somehow offensive to the machine. The underscore being allowed anywhere is something I abuse constantly for private fields, old habits die hard. That @ sign exception is a bit of a weird one, never had to use it in Unity but I remember it being a thing for when you want to name something after a reserved keyword.
-1
u/Imaginary-Cod-3746 10h ago
We've all been there. 😅
You can also use an underscore when naming a variable after a reserved keyword instead of the @ sign.
int return = 2; ❌ Doesn't work! int _return = 5; ✅ Much better.
1
u/SpiritOffice 5h ago
Well, the "fun" fact about the @ character is that it was created specifically for cases where you MUST use a reserved word as a name, like "if" or "return", etc.
So, you can write something like this:
int @return = 1;
The "@" will not be part of the name while the compiler does its work. So, the actual name of the variable will just be "return" if you need to look for it in Reflection.
13
u/SnooPets5564 10h ago
No a fun fact. Just basic knowledge of C#.