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.
- Integer Types:
sbyte: 8-bit signed integer (-128 to 127)byte: 8-bit unsigned integer (0 to 255)short: 16-bit signed integer (-32,768 to 32,767)ushort: 16-bit unsigned integer (0 to 65,535)int: 32-bit signed integer (-2,147,483,648 to 2,147,483,647)uint: 32-bit unsigned integer (0 to 4,294,967,295)long: 64-bit signed integerulong: 64-bit unsigned integer
- Floating-Point Types:
float: 32-bit single-precision floating-point numberdouble: 64-bit double-precision floating-point number (default for floating-point literals)decimal: 128-bit high-precision decimal type, suitable for financial calculations.
Boolean Type
bool: Represents a boolean value, which can be eithertrueorfalse.
Character Type
char: Represents a single character. It is typically used to store Unicode characters.
Reference Types
Unlike value types, reference types store a reference (or pointer) to the actual data, which is stored on the heap.
String Type
string: Represents a sequence of characters. Strings are immutable in C#, meaning their content cannot be changed after creation.
Example:
string message = "Hello, C#!";
int length = message.Length; // length will be 10
Object Type
object: The ultimate base type of all types in C#. An object variable can hold values of any 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
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!
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:
Nullable<T> variableName(generic form)T? variableName(shorthand, whereTis a value type)
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.