DEV Community

Cover image for C# Fundamentals: Variables and Data Types
Adrián Bailador
Adrián Bailador

Posted on

C# Fundamentals: Variables and Data Types

In this lesson, we’ll explore the fundamental concepts of variables and data types in C#. These two elements are essential for storing and handling information in your programs.

What is a Variable?

Variables are like containers that we use to store data in our programs. For example, if you want to store a person’s age, you can save it in a variable called age. Variables allow our programs to “remember” information while they run.

To declare a variable in C#, we follow this format:

type variableName = value;
Enter fullscreen mode Exit fullscreen mode

Where:

  • type: defines the kind of data the variable will store.
  • variableName: is the name you give the variable.
  • value: is the data you want to store in the variable.

Example:

int age = 28;
string name = "Peter";
double temperature = 21.5;
Enter fullscreen mode Exit fullscreen mode

In this case, we’ve declared a variable age of type int, a variable name of type string, and a variable temperature of type double.

Naming Conventions: Camel Case

In C#, it’s good practice to follow certain naming conventions to improve code readability. For naming variables, we generally use camelCase, where the variable name starts in lowercase and each new word begins with a capital letter, like myName or dateOfBirth.

Example of variables named in camelCase:

int numberOfStudents = 18;
string fullName = "Paul Garcia";
double productPrice = 29.99;
Enter fullscreen mode Exit fullscreen mode

These conventions make the code more readable and easier to understand, especially when working in a team.

Data Types in C

In C#, there are several basic data types you can use to define the kind of information each variable will store:

  1. int: for whole numbers, like 8, 105, or -20.
  2. double: for decimal numbers, like 4.8, 3.1416, or -7.28.
  3. string: for text, like "Hi Codu", "C# is the best".
  4. bool: for true/false values (true or false).

When to Use Each Data Type

  • int: Use int when you need to work with whole numbers (without decimals). It’s common in situations where you don’t need decimal values, like counting people or iterations in a loop.
  • double: Opt for double when you need to work with decimals, like in money calculations, temperatures, or percentages.
  • string: Use string whenever you’re working with text. It’s useful for names, addresses, messages, and any other textual data.
  • bool: Use bool for true or false values, ideal for conditions (for example, whether a user is logged in or not).

Type Conversion

In C#, sometimes you need to convert data from one type to another. There are two types of conversions:

  1. Implicit Conversion: This happens automatically when there’s no loss of information. For example, you can convert an int to double without issues, as double can contain whole numbers.

    int wholeNumber = 10;
    double decimalNumber = wholeNumber; // Implicit conversion from int to double
    
  2. Explicit Conversion: You need to tell C# to perform the conversion because information might be lost. This is done using a “cast”:

    double decimalValue = 9.8;
    int integerValue = (int)decimalValue; // Explicit conversion from double to int
    

    Here, integerValue will be 9, as the decimal portion is lost when converting to int.

You can also convert data using specific methods, like ToString() to convert to text or Parse() to transform text into a number.

int number = 42;
string text = number.ToString(); // Convert from int to string

string numberAsText = "123";
int convertedNumber = int.Parse(numberAsText); // Convert from string to int
Enter fullscreen mode Exit fullscreen mode

Another example is converting bool to string:

bool isActive = true;
string status = isActive.ToString(); // Result: "True"
Enter fullscreen mode Exit fullscreen mode

Practical Example: Average Calculator

Let’s look at a practical example where we’ll use variables, data types, and conversions. We’ll create an average calculator that takes three numbers and calculates their average.

using System;

class AverageCalculator
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the first number:");
        double number1 = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter the second number:");
        double number2 = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter the third number:");
        double number3 = Convert.ToDouble(Console.ReadLine());

        double average = (number1 + number2 + number3) / 3;

        Console.WriteLine("The average is: " + average);
    }
}
Enter fullscreen mode Exit fullscreen mode

This program prompts for three numbers, calculates their average, and displays it on the screen.

Practice Exercises

  1. Create a Text Variable: Declare a variable name of type string and assign it your name. Print a message saying "Hi, [name]".

  2. Store a Person’s Data: Create variables to store a person’s name, age, and body temperature (using string, int, and double). Then, print a message like: "My name is [name], I am [age] years old and my temperature is [temperature]°C".

  3. Type Conversion: Create a double variable with the value 6.9. Convert this value to int and display both values on the screen to see the difference.

Top comments (0)