Overview Languages Framework API Reference

C# Variables and Types

Understanding variables and data types is fundamental to programming in C#. This section covers the basic building blocks for storing and manipulating data.

Primitive Data Types

C# provides a rich set of built-in data types, often referred to as primitive or value types. These types directly contain their data.

Numeric Types

Used for storing numerical values. They differ in the range of values they can hold and the amount of memory they consume.

Boolean Type

Character Type

Reference Types

Unlike value types, reference types store a reference (or pointer) to the actual data, which is stored on the heap.

String Type

Example:

string message = "Hello, C#!";
int length = message.Length; // length will be 10
            

Object Type

Example:

object obj = 123;
obj = "This is a string";
obj = true;
            

Declaring and Initializing Variables

To declare a variable, you specify its type followed by its name. You can also initialize it with a value.

// Declaration
int age;

// Initialization
age = 30;

// Declaration and Initialization in one step
double price = 19.99;
string name = "Example Product";
bool isActive = true;
char initial = 'J';
            

Type Inference (var Keyword)

C# 3.0 introduced the var keyword, which allows the compiler to infer the type of a variable based on the value it is initialized with. The variable is still statically typed; its type is determined at compile time.

var count = 100; // Compiler infers 'int'
var pi = 3.14159; // Compiler infers 'double'
var greeting = "Welcome!"; // Compiler infers 'string'
var isComplete = false; // Compiler infers 'bool'

// 'var' cannot be used without initialization
// var temp; // Error
            
Use var when the type is obvious from the right-hand side of the assignment, which can make your code more concise and readable. However, avoid using var if it obscures the intended type.

Type Conversion (Casting)

Type conversion is the process of converting a value from one data type to another. There are two main types of conversions:

Implicit Conversion

Occurs automatically when a smaller data type is converted to a larger data type, and there's no loss of data.

int myInt = 10;
long myLong = myInt; // Implicit conversion from int to long
double myDouble = myLong; // Implicit conversion from long to double
            

Explicit Conversion (Casting)

Required when converting a larger data type to a smaller one, or when the conversion might result in a loss of data. You must explicitly tell the compiler what you intend.

double myDouble = 9.78;
int myInt = (int)myDouble; // Explicit conversion (casting) from double to int. Loses the fractional part. Result is 9.

long myLong = 10000000000L;
int myInt = (int)myLong; // Potential data loss. Be cautious!
            
Explicit casting can lead to data loss or unexpected behavior if not handled carefully. Always consider the implications.

Nullability

By default, reference types can be assigned the value null, indicating that they don't refer to any object. Value types (like int, bool) cannot be null by default.

To allow a value type to be nullable, you can use the nullable value type syntax:

int? nullableInt = null; // A nullable integer
bool? nullableBool = true;

if (nullableInt.HasValue) {
    Console.WriteLine(nullableInt.Value);
} else {
    Console.WriteLine("nullableInt is null.");
}

// Using the null-coalescing operator ??
int value = nullableInt ?? 0; // If nullableInt is null, use 0 instead.
            

Further Reading