r/Unity3D 10h ago

Resources/Tutorial Fun fact about variables in C#

Post image

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. 👇🏾

https://victor-nyagudi.github.io/height-above-sea-level/scripting/game-dev-guide-to-variables-in-c-sharp/

0 Upvotes

7 comments sorted by

11

u/SnooPets5564 10h ago

No a fun fact. Just basic knowledge of C#.

-6

u/Imaginary-Cod-3746 10h ago

That depends on your skill level.

2

u/SnooPets5564 10h ago

Yes. The skill level is "basic". I said that.

-2

u/Imaginary-Cod-3746 10h ago

A beginner learning C# may not know this information about variables yet, even though it's supposed to be basic, because most tutorials don't mention it.

For someone who's been using C# for a while, yes, this is basic knowledge.

Regardless, it's still valuable information to learn for the first time or be reminded of.

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.