1. 🔴 What is the difference between implicit and explicit type conversion?
Type conversion means converting a value from one data type to another data type.
C# supports two main types of conversion:
-
Implicit Conversion: Automatically performed by the compiler.
-
Explicit Conversion: Manually performed by the developer using casting.
Implicit Type Conversion
Implicit conversion happens automatically without requiring casting.
It is allowed when the compiler knows the conversion is valid without losing information for the supported conversion.
Example:
int number = 100;
double result = number;
Console.WriteLine(result); // 100
Explanation:
-
numberis anint. -
resultis adouble. -
C# automatically converts
intintodouble. -
No explicit casting is required.
Memory Flow:
int number = 100
|
v
Implicit Conversion
|
v
double result = 100.0
Explicit Type Conversion
Explicit conversion requires the developer to manually specify the target data type using casting.
It is commonly required when a conversion might lose information.
Example:
double number = 100.75;
int result = (int)number;
Console.WriteLine(result); // 100
Explanation:
-
numbercontains100.75. -
(int)explicitly converts the value into an integer. -
The decimal portion
.75is removed. -
The result becomes
100.
Memory Flow:
double number = 100.75
|
v
Explicit Conversion
(int)
|
v
int result = 100
Implicit vs Explicit Conversion
|
Implicit Conversion |
Explicit Conversion |
|---|---|
|
Automatic conversion |
Manual conversion |
|
No casting required |
Casting required |
|
Generally used for safe conversions |
Used when conversion may lose data |
|
Example: |
Example: |
|
Compiler performs conversion |
Developer specifies conversion |
Key Points
-
Implicit conversion does not require casting.
-
Explicit conversion requires casting.
-
Explicit conversion may cause data loss.
-
Not all data types can be converted using casting.
-
Convert.ToInt32()andint.Parse()are additional conversion methods, particularly useful when converting strings to integers.
Interview Answer: Implicit conversion is performed automatically by the compiler, whereas explicit conversion requires manual casting and may result in data loss.
2. 🟡 What are nullable value types and nullable reference types?
In C#, nullable types allow variables to represent the absence of a value using null.
There are two main categories:
-
Nullable Value Types
-
Nullable Reference Types
Nullable Value Types
Normally, value types such as int, bool, double, and DateTime cannot store null.
By adding ?, we can allow them to store null.
Example:
int number = 100;
// int age = null; // Compilation error
int? age = null;
age = 25;
Console.WriteLine(age); // 25
Explanation:
-
intcannot normally containnull. -
int?allows either an integer ornull. -
Internally,
int?representsNullable<int>.
Memory Illustration:
Normal Value Type
-----------------
int age = 25
age
|
v
[25]
Nullable Value Type
-------------------
int? age = null
age
|
v
[HasValue = false]
int? age = 25
age
|
v
[HasValue = true]
[Value = 25]
Important Nullable Value Type Properties
1. HasValue: Checks whether the variable contains a value.
2. Value: Returns the stored value. Throws an exception if the value is null.
3. GetValueOrDefault(): Returns the stored value or the type's default value.
Example:
int? age = null;
Console.WriteLine(age.HasValue); // False
Console.WriteLine(age.GetValueOrDefault()); // 0
age = 25;
Console.WriteLine(age.HasValue); // True
Console.WriteLine(age.Value); // 25
Nullable Reference Types
Reference types such as string, Employee, and Customer can hold null.
With nullable reference types enabled, C# distinguishes between references intended to contain a value and references that may be null.
Example:
#nullable enable
string name = "John";
string? city = null;
Console.WriteLine(name);
Console.WriteLine(city);
Explanation:
-
string nameindicates thatnameshould not benull. -
string? cityindicates thatcitycan benull. -
The compiler provides warnings when code may access a nullable reference without checking it.
Important: Nullable reference types are primarily a compile-time safety feature. They do not change how reference types are stored at runtime.
Handling Null Values
1. Null-Coalescing Operator (??)
Provides a default value when the variable is null.
string? name = null;
string result = name ?? "Guest";
Console.WriteLine(result); // Guest
2. Null-Conditional Operator (?.)
Safely accesses a member when the object might be null.
string? name = null;
int? length = name?.Length;
Console.WriteLine(length ?? 0); // 0
Nullable Value Types vs Nullable Reference Types
|
Nullable Value Type |
Nullable Reference Type |
|---|---|
|
Used with value types |
Used with reference types |
|
Example: |
Example: |
|
Uses |
Uses compiler nullability annotations |
|
Has |
Does not have |
|
Can represent a missing value |
Helps detect possible null-reference errors |
Real-Time Example in ASP.NET Core Web API
public class EmployeeDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int? Age { get; set; }
public string? MiddleName { get; set; }
public DateTime? ResignationDate { get; set; }
}
Explanation:
-
Id: Required integer value. -
Name: Intended to be non-null. -
Age: Optional integer. -
MiddleName: Optional string. -
ResignationDate: Optional date.
Nullable annotations express intent but do not automatically enforce API request validation.
Key Points
-
Nullable value types use
?to allownull. -
int?is shorthand forNullable<int>. -
Nullable value types support
HasValue,Value, andGetValueOrDefault(). -
Nullable reference types help identify possible null-reference errors at compile time.
-
Use
??to provide default values. -
Use
?.to safely access nullable objects. -
Nullable reference type analysis must be enabled in the project or code.
Interview Answer: Nullable value types allow value types to store null using Nullable<T>, whereas nullable reference types help the compiler identify references that may contain null, reducing null-reference errors.
Quick Interview Revision
|
Concept |
Key Point |
|---|---|
|
Implicit Conversion |
Automatic conversion without casting |
|
Explicit Conversion |
Manual conversion using casting |
|
|
Nullable integer |
|
|
Nullable reference annotation |
|
|
Checks whether a nullable value type contains a value |
|
|
Retrieves the stored value |
|
|
Provides a default value when null |
|
|
Safely accesses nullable objects |
Important Interview Tip: Remember these examples: int → double for implicit conversion, double → int for explicit conversion, int? for nullable value types, and string? for nullable reference types.