MSDN Documentation

.NET Core Tutorials: Core Concepts

Understanding Variables in .NET Core

Variables are fundamental building blocks in any programming language, including .NET Core. They act as named containers for storing data that your program can manipulate and reference throughout its execution.

Declaring Variables

To use a variable, you first need to declare it. Declaration involves specifying the variable's data type and its name. In C#, the syntax for declaring a variable is:

<data_type> <variable_name>;

For example, to declare an integer variable named `numberOfStudents`:

int numberOfStudents;

This statement tells the compiler that `numberOfStudents` will hold integer values.

Initializing Variables

While you can declare a variable, it's good practice to initialize it with a value. Initialization assigns an initial value to the variable. You can do this at the time of declaration or later.

Declaration and Initialization Together:

string greeting = "Hello, .NET Core!"; double price = 19.99; bool isComplete = false;

Separate Declaration and Initialization:

int counter; // Declaration counter = 0; // Initialization char initial; initial = 'A';

If you don't initialize a variable, attempting to use its value will result in a compile-time error, as the compiler cannot guarantee its initial state.

Common Variable Types in .NET Core

.NET Core supports a wide range of data types. Here are some of the most commonly used primitive types:

You can also use the var keyword for implicit typing. The compiler infers the type based on the assigned value:

var message = "This is a string."; // Inferred as string var count = 100; // Inferred as int var isActive = true; // Inferred as bool

Variable Scope

The scope of a variable refers to the region of your code where the variable is accessible. Variables are typically declared within blocks of code (e.g., inside methods, loops, or conditional statements).

Variables declared inside a method are local to that method and cannot be accessed from outside.

public void MyMethod() { int localVar = 5; // localVar is only accessible within MyMethod Console.WriteLine(localVar); } // Console.WriteLine(localVar); // This would cause a compile-time error

Naming Conventions

Adhering to consistent naming conventions makes your code more readable and maintainable. For variables in C#/.NET Core, the convention is:

Avoid using single-letter variable names unless they are loop counters (like `i`, `j`) or have a very clear, localized meaning.

Understanding and effectively using variables is a crucial step in your journey with .NET Core development. They are the fundamental elements that allow you to store, retrieve, and manipulate data, powering the logic of your applications.