C# Type Checking and Type Casting – Difference Between is, as, and Explicit Casting
In C#, is, as, and explicit casting are used to check or convert between compatible types.
The main difference is how they handle type checking, conversion, and invalid casts.
-
is– Checks whether an object is compatible with a specified type. -
as– Attempts a reference or nullable conversion and returnsnullif it fails. -
Explicit Casting
(Type)– Performs a conversion and can throw an exception if the conversion is invalid.
1. What is the is operator in C#?
The is operator is used to check whether an object is compatible with a particular type.
It returns true or false.
Example
object value = "Hello";
bool result = value is string;
Console.WriteLine(result); // True
Explanation
-
valueis declared asobject. -
It contains a string value
"Hello". -
value is stringchecks whether the object is compatible withstring. -
Since the object is a string, the result is
true. -
No exception is thrown if the type does not match.
Example: Checking different types
object value = 100;
Console.WriteLine(value is int); // True
Console.WriteLine(value is string); // False
Console.WriteLine(value is double); // False
How is works
object value = "Hello"
|
v
value is string
|
v
Is value a string?
|
+------+------+
| |
Yes No
| |
v v
True False
Modern C#: Pattern Matching with is
The is operator also supports pattern matching, allowing type checking and variable declaration together.
object value = "Hello";
if (value is string text)
{
Console.WriteLine(text.Length); // 5
}
Explanation:
-
value is stringchecks the type. -
textreceives the string reference when the check succeeds. -
No separate explicit cast is required.
-
The variable
textcan be used within the scope where it is definitely assigned.
Key Points
-
Purpose: Checks whether an object matches a specified type.
-
Return Type:
bool. -
Invalid Type: Returns
false, rather than throwing a casting exception. -
Null:
null is stringreturnsfalse. -
Pattern Matching: Supports type checking and variable declaration together.
-
Inheritance: Can check whether an object implements an interface or derives from a class.
-
Common Usage: Type validation, pattern matching, and safe conditional processing.
2. What is the as operator in C#?
The as operator is used to attempt a conversion to a compatible reference type or nullable value type.
If the conversion succeeds, it returns the converted reference or nullable value.
If the conversion fails, it returns null instead of throwing an exception.
Example
object value = "Hello";
string? text = value as string;
Console.WriteLine(text); // Hello
Explanation
-
valuecontains a string. -
value as stringattempts to convert it tostring. -
Since the conversion is valid,
textreferences"Hello". -
If the conversion were invalid,
textwould benull.
Example: Invalid conversion
object value = 100;
string? text = value as string;
Console.WriteLine(text == null); // True
Why?
The boxed integer cannot be converted into a string reference using as.
Instead of throwing an exception, the operation returns null.
How as works
object value = "Hello"
|
v
value as string
|
v
Is conversion valid?
|
+------+------+
| |
Yes No
| |
v v
Return string Return null
|
v
text = "Hello"
Example: Using as with null checking
object value = "Hello";
string? text = value as string;
if (text != null)
{
Console.WriteLine(text.Length);
}
else
{
Console.WriteLine("Invalid type");
}
Can we use as with value types?
Not directly with a non-nullable value type.
Incorrect:
object value = 100;
// int number = value as int; // Compile-time error
Correct using nullable value type:
object value = 100;
int? number = value as int?;
Console.WriteLine(number); // 100
The as operator supports nullable value types such as int?, but not non-nullable value types such as int.
Key Points
-
Purpose: Attempts a safe type conversion.
-
Return Value: Converted value or
null. -
Invalid Conversion: Returns
null. -
Exception: Does not throw
InvalidCastExceptionfor an unsuccessful compatibleasconversion. -
Supported Types: Reference types and nullable value types.
-
Null Checking: Usually required before accessing converted members.
-
Performance: Avoids exceptions for unsuccessful casts.
-
Common Usage: Optional conversions when an incompatible type is an expected possibility.
3. What is explicit casting in C#?
Explicit casting is used to convert a value or reference from one type to another using the target type in parentheses.
For reference-type casts and unboxing, an invalid conversion can throw InvalidCastException.
Unlike as, explicit casting does not return null merely because the runtime type is incompatible.
Example
object value = "Hello";
string text = (string)value;
Console.WriteLine(text); // Hello
Explanation
-
valuecontains a string object. -
(string)valueexplicitly converts the reference tostring. -
The runtime verifies that the conversion is valid.
-
Since the object is a string, the conversion succeeds.
Example: Invalid casting
object value = 100;
string text = (string)value;
Result:
System.InvalidCastException
Why?
The object contains a boxed integer, not a string.
The explicit reference conversion fails at runtime.
How explicit casting works
object value = "Hello"
|
v
(string)value
|
v
Is conversion valid?
|
+------+------+
| |
Yes No
| |
v v
Return string Throw Exception
| |
v v
text="Hello" InvalidCastException
Example: Numeric explicit casting
Explicit casting can also be used for numeric conversions.
double salary = 50000.75;
int amount = (int)salary;
Console.WriteLine(amount); // 50000
Explanation:
-
salarycontains50000.75. -
(int)salaryconverts the double into an integer. -
The fractional portion is discarded.
-
This is a numeric conversion, not an object reference cast.
Important: Numeric casts have different rules from reference casts. For example, overflow behavior depends on whether the conversion occurs in a checked or unchecked context.
Key Points
-
Purpose: Explicitly converts between compatible types.
-
Syntax:
(TargetType)value. -
Invalid Reference Cast: Throws
InvalidCastException. -
Runtime Validation: Used for casts that require checking an object's runtime type.
-
Numeric Conversion: Supports conversions such as
doubletoint. -
Unboxing: Uses explicit casting to extract a value from a boxed object.
-
Common Usage: Downcasting, unboxing, and numeric conversions.
4. Difference Between is, as, and Explicit Casting
|
Feature |
|
|
Explicit Casting |
|---|---|---|---|
|
Main purpose |
Type checking |
Safe conversion attempt |
Type conversion |
|
Syntax |
|
|
|
|
Result |
|
Converted value / |
Converted value |
|
Invalid runtime type |
Returns |
Returns |
Usually throws |
|
Reference types |
Yes |
Yes |
Yes |
|
Nullable value types |
Supports type patterns |
Yes |
Yes |
|
Non-nullable value types |
Supports type patterns |
No |
Yes |
|
Numeric conversions |
Not for numeric conversion |
No |
Yes |
|
Pattern matching |
Yes |
No |
No |
|
Main usage |
Validate type |
Optional conversion |
Required conversion |
5. Complete Example – All Three Together
class Program
{
static void Main()
{
object value = "Hello";
// 1. IS
if (value is string)
{
Console.WriteLine("Value is a string");
}
// 2. AS
string? text1 = value as string;
Console.WriteLine(text1); // Hello
// 3. EXPLICIT CASTING
string text2 = (string)value;
Console.WriteLine(text2); // Hello
}
}
Execution flow
object value
|
+------------+-------------+
| | |
v v v
is as Explicit Cast
| | |
v v v
Check Type Try Convert Convert Type
| | |
v v v
true/false Value/null Value/Exception
| | |
v v v
Validation Safe Attempt Required Cast
6. Important Interview Scenarios
Scenario 1: Checking object type before processing
Use is.
object value = "JNTech";
if (value is string text)
{
Console.WriteLine(text.ToUpper());
}
Why is? Because we want to check the type and process the value only if the check succeeds.
Scenario 2: Attempting an optional conversion
Use as.
object value = "JNTech";
string? name = value as string;
if (name != null)
{
Console.WriteLine(name);
}
Why as? Because conversion failure is expected and can be handled using a null check.
Scenario 3: Converting a base class to a derived class
Use explicit casting when the actual object type is known.
public class Employee
{
public int Id { get; set; }
}
public class Manager : Employee
{
public string Department { get; set; } = "";
}
Usage:
Employee emp = new Manager
{
Id = 101,
Department = "IT"
};
Manager manager = (Manager)emp;
Console.WriteLine(manager.Department); // IT
Why explicit casting?
The variable emp is declared as Employee, but the actual object is a Manager.
The explicit cast converts the base-class reference into a derived-class reference.
Scenario 4: Invalid downcasting
Employee emp = new Employee();
Manager manager = (Manager)emp;
Result:
System.InvalidCastException
The actual object is an Employee, not a Manager.
A safer alternative is:
if (emp is Manager manager)
{
Console.WriteLine(manager.Department);
}
7. Important Interview Follow-up Questions
Q1. What is the main difference between is and as?
is checks whether a value matches a type and returns a Boolean result. as attempts a conversion and returns the converted value or null.
Q2. What happens when as conversion fails?
It returns null instead of throwing InvalidCastException.
Q3. What happens when explicit reference casting fails?
It throws InvalidCastException at runtime.
Q4. Can we use as with int?
Not directly. as requires a reference type or nullable value type such as int?.
Q5. Does is perform casting?
A basic is expression checks the type. With pattern matching, it can also assign the successfully matched value to a variable.
Q6. Which is better: is or as?
Use is pattern matching when you need to check a type and then use the typed value. Use as when a nullable conversion result is convenient.
Q7. Can explicit casting convert double to int?
Yes.
double value = 10.75;
int number = (int)value;
Console.WriteLine(number); // 10
Q8. Can we use is to check an interface?
Yes.
if (obj is IDisposable disposable)
{
disposable.Dispose();
}
This checks whether the object implements IDisposable.
Quick Interview Revision
|
Keyword |
Remember |
|---|---|
|
|
Checks type compatibility |
|
|
Attempts conversion; returns |
|
|
Explicit conversion |
|
|
Returns Boolean |
|
|
Supports reference and nullable value types |
|
Explicit casting |
Can throw |
|
|
Type checking with pattern matching |
|
|
Safe conversion attempt |
|
|
Explicit reference cast |
Interview Answer:
is is used to check whether an object is compatible with a specified type and returns true or false. as attempts to convert an object to a reference or nullable value type and returns null if the conversion fails. Explicit casting uses (Type) syntax to perform a conversion and can throw InvalidCastException if an object cannot be cast to the requested type. In modern C#, is pattern matching is often preferred when both type checking and accessing the converted value are required.