Variables and Data Types

Explore C#'s syntax by creating variables and learning about data types.

Variables

No app is useful if it can’t store and process information. In this context, variables are important.

Variables are used to store data within a program. They represent a named area of computer memory that holds a value of a particular type. The type determines what kind of information a variable can store.

The basic syntax for declaring a variable is as follows:

variable_type variable_name;

Valid variable names must meet the following requirements:

  • The name can contain an underscore and any number and letter, while the first character in the name must be a letter or underscore.
  • The name can’t contain punctuation marks or spaces.
  • We can’t use a C# keyword as a variable name.

Although we can give any name to our C# variables, it’s highly recommended to use descriptive names. For instance, if we want to store a person’s first name, we can declare a variable as follows:

string name;

In the example above, we create a variable called name that has the string type. The string objects represent text.

Remember that C# is case-sensitive, so the following two variable definitions represent two different variables:

string name;
string Name;

We’ve declared a variable, but it doesn’t contain any information yet. To assign a value to a variable, we use the assignment (=) operator.

name = "John";

We can combine declaration and assignment in one line. This operation is called initialization.

string lastName = "Doe";

We get an error during compilation if we try to assign a value to a variable that wasn’t declared:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy