Skip to main content
Published on

Variables in C#

Share:

Introduction

Variables are fundamental in any programming language, as they serve as containers for storing values that are used and manipulated throughout the program. In C#, the definition and use of variables follow specific rules and conventions.

Understanding Variables in C#

A variable, in simple terms, is a space allocated in memory that stores values. In C#, each variable has a specific type, which defines the nature of the data it can hold.

  • The variable's type determines the size of the memory space the variable will occupy.
  • In some languages, it is not mandatory to declare the type of a variable. However, in C#, the type is essential to ensure data safety and integrity.

Types of Variables in C#

C# offers a variety of variable types. In this article, we focus on the most common ones:

  • Integer (int): Used to store whole numbers.
  • Decimal (double): Suitable for decimal or floating-point numbers.
  • String: Used to represent sequences of characters.
  • Char: Stores a single character.
  • Boolean (bool): Represents true or false values.

It is worth mentioning that C# also has arrays, lists, dictionaries, and many other types. These will be discussed in detail in future posts.

Practical Example

using System;

namespace Base {
  class Variables {
    public void Run() {
      int integer = 10;
      double _double = 10.5;
      string _string = "I am a string.";
      char character = 'c';
      bool boolean = true;

      Console.WriteLine("integer: " + integer); // integer: 10
      Console.WriteLine("double: " + _double); // double: 10.5
      Console.WriteLine("string: " + _string); // string: I am a string.
      Console.WriteLine("character: " + character); // character: c
      Console.WriteLine("boolean: " + boolean); // boolean: True
    }
  }
}

Conclusion

Mastering the concept of variables and understanding the different types available in C# is crucial for any programmer. This foundational knowledge forms the basis upon which the logic and functionality of C# applications are built.

Happy coding!