Start learning free

LESSON 11 OF 674 · VARIABLES

Variable Naming Rules in C#

Lesson

TL ; DR:

  • In C#, we use the camelCase convention to name our variables. It implies separating different words with capital letters, like this:

    string companyName = "Apple";
    
    int foundingYear = 1976;
    
    bool isUnicorn = true;
    
    int numberOfEmployees = 137000;
    



Full lesson:

Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.

Bad variable names:

int 18spam;
string x.15;
bool #name;

If you try to create a variable with any of these names, C# will throw an error.


Naming conventions: camelCase and snake_case

Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:

string first name = "Kate";

This code will also throw an error.

When you name your variables, you want to use one of these two conventions:

snake_case = separate different words with an underscore (_), like this:

string first_name = "Jane";
string last_name = "Doe";

camelCase = separate different words with capital letters, like this:

string firstName = "Jane";
string lastName = "Doe";

It's important to be consistent with the casing technique you use. Do not combine both of them in the same code, like this:

string first_name = "Jane";
string lastName = "Doe";

Case sensitive:

Variable names are case sensitive:

string name = "Kate";
string Name = "Andy";
string NAME = "George";

Console.WriteLine(name + " " + Name + " " + NAME); // Output: Kate Andy George

Although C# allows us to do this, it's always confusing and a bad coding practice to differentiate variable names just by case!


Mnemonic Variable Names:

Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".

Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.

Here is a great example:

int a = 25;
int b = 13;
int c = a * b;
Console.WriteLine(c);

compared to:

int hours = 25;
int rate = 13;
int pay = hours * rate;
Console.WriteLine(pay);

C# understands and is happy with both of these pieces of code. But it's clearly which version makes your reader happier.


Assignment
Follow the Coding Tutorial and let's let's name some variables well!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check