Data Types in C#

9 questions found

What are the 2 broad classifications of data types available in C#?

Beginner
C# data types fall into two broad classifications called value types and reference types. Value types, such as int, double, and bool, store their actual data directly in the memory location of the variable itself, usually on the stack, while reference types, such as classes, arrays, and strings, store a reference or pointer to the actual data, which lives on the heap, meaning the variable itself simply holds an address pointing to that data.
int number = 10;             // value type, stores 10 directly
Customer customer = new Customer(); // reference type, stores an address
Real-world example A developer debugging unexpected shared state realizes that two variables pointing to the same Customer object, a reference type, were both affected by a single change, while similar confusion never happens with simple value types like int.

Common follow-ups: What are examples of value types and reference types in C#?;How does this classification affect how variables are passed to methods?

What are the differences between value types and reference types?;What do you mean by casting a data type?

How do you create user-defined data types in C#?

Intermediate
You create user defined data types in C# using constructs like class, struct, enum, and interface, each serving a different purpose. A class or struct lets you group related fields and methods into a single custom type representing a real world concept, an enum lets you define a fixed set of named constant values, and an interface lets you define a contract of members that implementing types must provide.
public struct Point {
    public int X;
    public int Y;
}

public enum OrderStatus {
    Pending, Shipped, Delivered
}
Real-world example An e commerce application defines a custom OrderStatus enum to represent the fixed set of possible order states, making the code far more readable and less error prone than using plain integers or strings to represent the same statuses.

Common follow-ups: What is the difference between defining a custom type as a class versus a struct?;When should you use an enum instead of a set of constant integers?

What are the 2 broad classifications of data types available in C#?;Difference between int and Int32 in C#

Difference between int and Int32 in C#

Beginner
int is simply a C# keyword alias for the System.Int32 struct provided by the Base Class Library, meaning both represent exactly the same 32 bit signed integer type and can be used completely interchangeably. There is no difference in behavior or performance between them, and the choice between using int or Int32 is purely a matter of coding style and readability preference.
int number1 = 100;
System.Int32 number2 = 100;
// Both lines create the exact same type of value
Real-world example A coding standards document at a company simply recommends using the lowercase int keyword everywhere instead of Int32, purely for consistency with common C# conventions, since both compile down to the identical underlying type.

Common follow-ups: Are there similarly aliased types for other numeric types like long or short?;Does using int versus Int32 ever matter when working with generics or reflection?

What is the difference between string keyword and System.String class?;What are the differences between value types and reference types?

What are the differences between value types and reference types?

Beginner
Value types store their actual data directly within their own memory allocation, typically on the stack, and copying a value type variable creates a completely independent copy of the data, so changing one copy does not affect the other. Reference types store a reference to data located on the heap, so copying a reference type variable only copies the reference itself, meaning both variables end up pointing to and sharing the exact same underlying object, and changing the data through one variable is visible through the other as well.
int a = 5;
int b = a;
b = 10; // a is still 5

Customer c1 = new Customer { Name = "Ali" };
Customer c2 = c1;
c2.Name = "Sara"; // c1.Name is now also "Sara"
Real-world example A developer fixing a bug discovers that modifying one Customer object unexpectedly changed a second variable's data as well, and realizes both variables were simply referencing the exact same object in memory since Customer is a reference type.

Common follow-ups: What are structs and why are they considered value types even though they can contain multiple fields?;How does passing value types versus reference types into a method differ?

What are the 2 broad classifications of data types available in C#?;What is Boxing and Unboxing in C#?

What do you mean by casting a data type?

Beginner
Casting a data type means explicitly converting a value from one data type to another, such as converting a double to an int, which C# allows either implicitly when there is no risk of data loss or explicitly using cast syntax when the conversion might lose information or fail. Casting tells the compiler that you are intentionally aware of and accepting any potential data loss or risk involved in the conversion.
double price = 19.99;
int roundedPrice = (int)price; // explicit cast, roundedPrice becomes 19
Real-world example A pricing calculation that works with decimal values casts the final result to an int when displaying a simplified whole number price on a product listing page, intentionally discarding the decimal portion for display purposes.

Common follow-ups: What is the difference between casting and using a conversion method like Convert.ToInt32?;What happens if an explicit cast is not possible between two types?

What is the difference between an implicit conversion and an explicit conversion?;What are the 2 kinds of data type conversions available in C#?

What are the 2 kinds of data type conversions available in C#?

Beginner
C# supports two kinds of data type conversions called implicit conversions and explicit conversions. Implicit conversions happen automatically and safely, without any risk of data loss, such as converting an int to a double, while explicit conversions require you to manually specify the conversion using cast syntax, since they carry a risk of data loss or failure, such as converting a double to an int or converting between incompatible reference types.
int wholeNumber = 10;
double decimalNumber = wholeNumber; // implicit, always safe

double price = 19.99;
int roundedPrice = (int)price; // explicit, requires a cast
Real-world example A calculation engine automatically widens an int value into a double implicitly when combining it with other decimal values, while requiring an explicit cast whenever a decimal result needs to be narrowed back down into a whole number.

Common follow-ups: What is the difference between an implicit conversion and an explicit conversion?;Are there conversions that require calling a method instead of using a cast at all?

What is the difference between an implicit conversion and an explicit conversion?;What do you mean by casting a data type?

What is the difference between an implicit conversion and an explicit conversion?

Beginner
An implicit conversion happens automatically without requiring any special syntax, since the compiler knows the conversion is always safe and will not lose data, such as converting an int to a long. An explicit conversion, in contrast, requires you to manually write a cast using parentheses around the target type, because the compiler cannot guarantee the conversion will succeed without potential data loss, such as converting a long back down to an int, which requires you to explicitly acknowledge that risk.
long bigNumber = 100;      // implicit conversion from int to long
int smallNumber = (int)bigNumber; // explicit conversion from long to int
Real-world example A financial calculation stores intermediate results as a long to avoid overflow issues implicitly during addition, but requires an explicit cast whenever the final result needs to be stored back into a smaller int based field.

Common follow-ups: Which specific type conversions in C# are always implicit?;What happens at runtime if an explicit conversion cannot actually succeed?

What are the 2 kinds of data type conversions available in C#?;What do you mean by casting a data type?

What is Boxing and Unboxing in C#?

Intermediate
Boxing is the process of converting a value type, such as an int, into a reference type by wrapping it inside an object, allowing it to be treated like any other reference type object, while unboxing is the reverse process of extracting that original value type back out of the object wrapper. Both operations happen automatically or through simple casting, but they carry a performance cost since boxing allocates new memory on the heap and unboxing requires a runtime type check.
int number = 42;
object boxed = number;       // boxing
int unboxed = (int)boxed;    // unboxing
Real-world example A legacy method that only accepts parameters of type object receives an int argument, causing it to be automatically boxed into an object, and the method later unboxes it back into an int to perform calculations.

Common follow-ups: Why does boxing negatively affect performance?;How do generics help avoid unnecessary boxing and unboxing?

What happens during the process of boxing?;What are the differences between value types and reference types?

What happens during the process of boxing?

Intermediate
During boxing, the runtime allocates a new block of memory on the heap, copies the value type's data into that newly allocated memory, and wraps it inside an object reference, meaning the original stack based value type and the new heap based boxed object become two completely separate pieces of memory holding a copy of the same value. This copy step is exactly why changes made to the boxed object do not affect the original value type variable, and vice versa.
int original = 5;
object boxed = original;  // heap allocation happens here, a copy of 5 is stored
original = 10;
Console.WriteLine(boxed); // still prints 5, because boxed holds a separate copy
Real-world example A performance sensitive application processing millions of numeric values in a loop avoids storing them in a non generic ArrayList, which would box every single value, and instead uses a generic List<int> to avoid the repeated heap allocations entirely.

Common follow-ups: Why do generic collections like List<T> avoid the boxing overhead that non generic collections like ArrayList have?;Is there a way to check how much boxing is occurring in an application?

What is Boxing and Unboxing in C#?;What are the differences between value types and reference types?