Understanding data types and variables in C# is fundamental to writing efficient and correct C# programs. This tutorial covers the complete range of data types, how variables are declared, value and reference types, nullable types, and best practices for choosing the right data type.
In C#, a data type defines the type of data a variable can hold. It is a statically typed language, meaning the type of variable must be known at compile time. C# data types are categorized mainly into two groups:
Value types store the actual data in memory. They are allocated on the stack and are faster in access. When a value type is assigned to another, the data is copied.
// Integer type
int age = 30;
// Float type
float temperature = 36.6f;
// Boolean type
bool isActive = true;
// Character type
char grade = 'A';
Reference types store the reference to the memory location, not the actual data. They are allocated on the heap and can be more complex structures like objects, arrays, and strings.
// String is a reference type
string name = "John Doe";
// Object is base class for all types
object obj = 45;
// Array is also a reference type
int[] scores = { 85, 90, 95 };
Variables are containers for storing data values. In C#, you must declare a variable before using it. The syntax is:
dataType variableName = value;
int count = 10;
double salary = 45000.75;
string city = "New York";
The var keyword lets the compiler infer the data type based on the value. It must be initialized at the time of declaration.
var result = 100; // inferred as int
var message = "Hello"; // inferred as string
byte // 0 to 255
sbyte // -128 to 127
short // -32,768 to 32,767
ushort // 0 to 65,535
int // -2,147,483,648 to 2,147,483,647
uint // 0 to 4,294,967,295
long // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong // 0 to 18,446,744,073,709,551,615
float // 6-9 digits precision
double // 15-17 digits precision
decimal // 28-29 digits precision (used in financial calculations)
char // A single Unicode character
bool // true or false
string // sequence of characters
object // base type of all types in .NET
Value types cannot hold null by default. But by using nullable types (indicated by `?`), you can assign null to value types.
int? age = null;
if (age.HasValue) {
Console.WriteLine("Age: " + age.Value);
} else {
Console.WriteLine("Age not specified.");
}
Each data type in C# has a default value:
int defaultInt = default(int); // 0
bool defaultBool = default(bool); // false
object defaultObj = default(object); // null
Constants are immutable values known at compile-time.
const double PI = 3.14159;
Readonly variables can be assigned only in constructor or declaration. They are evaluated at runtime.
readonly int creationYear = 2025;
The dynamic type allows operations to bypass compile-time type checking. Type is resolved at runtime.
dynamic data = 100;
Console.WriteLine(data);
data = "C# Programming";
Console.WriteLine(data);
Boxing is converting a value type to object. Unboxing is retrieving value from object.
// Boxing
int num = 123;
object obj = num;
// Unboxing
int unboxed = (int)obj;
Declared inside a method and accessible only within it.
void Display() {
int temp = 10;
Console.WriteLine(temp);
}
Declared within class but outside methods. Accessible within the class.
class Sample {
int count = 5;
void Show() {
Console.WriteLine(count);
}
}
int x = 100;
long y = x; // No data loss
double pi = 3.14;
int intPi = (int)pi; // Data loss possible
string numStr = "123";
int number = Convert.ToInt32(numStr);
var is type-safe and resolved at compile time, while dynamic is resolved at runtime.
var x = 10; // int
dynamic y = 10; // dynamic, can change type
y = "Now string"; // no errorMastering C# data types and variables is essential for every C# developer. This tutorial gave you a comprehensive understanding of different data types, how they behave, and how to effectively declare and use variables. Whether youβre building a console app or enterprise solution, choosing the right data type improves performance, memory usage, and code clarity.
Copyrights © 2024 letsupdateskills All rights reserved