C# Variables and Data Types for Beginners

Variables give a C# program a place to store values so those values can be used later. A variable has a type, a name, and a value. Choosing an appropriate type makes code easier to understand and helps the compiler catch mistakes.

Common C# types

string name = "Dhilip";
int age = 31;
double price = 99.50;
bool isActive = true;

string stores text, int stores whole numbers, double stores floating-point numbers, and bool stores true or false.

Choosing a type

Use int for values that are naturally whole numbers, such as a count of records. Use string for text and bool for a yes/no state. Decimal values often use double; financial applications commonly need decimal when decimal precision is important.

Using var

var city = "Chennai";
var count = 10;

C# infers the type from the expression assigned to the variable. In the example, city is still a string and count is still an int. var does not make the variable dynamically typed.

Changing values

int score = 10;
score = 20;

A variable can receive another value compatible with its type. This is useful when a program calculates a new result or updates state while it runs.

Type conversions

string text = "42";
int number = int.Parse(text);

The original value is text, so it must be converted before it can be used as an integer. For user input, APIs such as int.TryParse are often safer because they let you handle invalid input without an exception.

Value versus reference examples

Primitive numeric types such as int hold their values directly. Types such as classes are reference types. Understanding this distinction becomes important when passing objects to methods and changing shared state.

Common beginner mistakes

Next step

Learn how a C# program makes decisions and repeats work in C# if, else, and Loops.

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.