0
0
CsharpHow-ToBeginner · 3 min read

How to Declare Variables in C#: Syntax and Examples

In C#, you declare a variable by specifying its type followed by the variable name, like int age;. You can also assign a value when declaring, for example, string name = "Alice";. This tells the computer to reserve space for that data type and optionally store a value.
📐

Syntax

To declare a variable in C#, you write the type of data you want to store, then the variable name. Optionally, you can assign a value right away.

  • type variableName; - declares a variable without a value.
  • type variableName = value; - declares and assigns a value.

The type tells the computer what kind of data the variable will hold, like numbers or text.

csharp
int age;
string name = "Alice";
💻

Example

This example shows how to declare variables of different types and print their values to the console.

csharp
using System;

class Program
{
    static void Main()
    {
        int age = 30;
        double height = 5.9;
        string name = "Alice";
        bool isStudent = true;

        Console.WriteLine($"Name: {name}");
        Console.WriteLine($"Age: {age}");
        Console.WriteLine($"Height: {height}");
        Console.WriteLine($"Is Student: {isStudent}");
    }
}
Output
Name: Alice Age: 30 Height: 5.9 Is Student: True
⚠️

Common Pitfalls

Common mistakes when declaring variables include:

  • Forgetting to specify the type, which causes a compile error.
  • Using a variable before it is assigned a value.
  • Trying to assign a value of the wrong type (like putting text in an int variable).
  • Using invalid variable names (like starting with a number or using spaces).

Always declare variables with a valid type and name, and assign values compatible with the type.

csharp
/* Wrong: missing type */
// age = 25; // Error: The name 'age' does not exist in the current context

/* Wrong: assigning wrong type */
// int number = "hello"; // Error: Cannot convert string to int

/* Right way */
int age = 25;
string greeting = "hello";
📊

Quick Reference

ConceptExampleDescription
Declare without valueint count;Creates a variable named count of type int without assigning a value.
Declare with valuestring city = "Paris";Creates and assigns the string "Paris" to city.
Valid typesint, double, string, boolCommon data types for numbers, text, and true/false values.
Invalid nameint 1stNumber;Variable names cannot start with a number.
Assign compatible valuebool isOpen = true;Value must match the variable's type.

Key Takeaways

Always specify the variable type before the name when declaring in C#.
You can declare a variable with or without assigning a value immediately.
Variable names must follow rules: start with a letter or underscore, no spaces.
Assign values that match the declared type to avoid errors.
Use meaningful variable names to make your code easier to read.