Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to create variables in C#

Theodore Kelechukwu Onyejiaku

A variable is like a container. It is used to store a value or content. The content it stores is a value and can be any kind of content. A typical example is a bottle of water; it is used to store a type of content called water. The bottle here is the variable and the value is the water.

Fig 1: Illustration of a variable and the value it stores

In C#, creating a variable is easy. It is no different from the usual pattern of creating variables in other languages.

As noted earlier, containers (variables) have a specific kind of content (value). For example, a water bottle is used to hold a value of type water. So, for us to create a variable, we must first know the type of content or value it should contain.

Data or value types in C#

The various data types in C# include:

  • Integer types: int, short, long, char, etc.
  • Decimal: Decimal
  • Floating point types: floating point numbers and double
  • Boolean: true or false values
  • Nullable types

So, our variables in C# must contain any of the data types above.

Defining variables

Variable definition is a way of specifying the kind of values our containers should have. It is when we say water should only be stored in this cup and only a bunch of keys should be in a particular box. It goes like this: data_type variable_name. See the code snippet below:

int age, yearOfBirth;
char gender, initial;
float salary, price;
bool isDelivered, pending;
Variable declaration

In the code snippet above, we created variables such as age, salary, isDelivered, etc., and specified the type of data they should contain. That is variable definition.

Variable assignment or initialization

This is when we give values to our variables. We must make sure that the value we give to our variables correlates with the variable definition.

The format goes this way: variable_name = value. See example below:

age = 20;
gender = "M";
price = 300.00;
Variable assignment

Code example

We defined variables, initialized them, and printed their values to the console in the code below.

// create class
class Variables
    // main method
    static void Main()
        // define variables
        int age;
        char sex;
        bool isMarried;
        double salary;
        int yearOfBirth;

        // initialize variables
        age = 100;
        sex = 'M';
        isMarried = false;
        yearOfBirth = 1921;
        salary = 1800.50;

        // print variable values to console




Theodore Kelechukwu Onyejiaku

View all Courses

Keep Exploring