Author: Microsoft Certified .NET Expert | 1-on-1 Training Available
Contact: +91-9331897923 | Website: supernovaservices.com
Casting allows you to convert one data type to another, helping you write flexible, reusable, and type-safe code. It's especially useful when dealing with base classes, interfaces, and general-purpose collections like List
.
object obj = 123;
int x = (int)obj;
Use when youβre sure of the type. Throws an exception if itβs wrong.
as
object obj = "hello";
string str = obj as string; // null if obj is not a string
Returns null
instead of throwing exceptions. Works with reference types and nullable value types.
is
if (obj is int number)
{
Console.WriteLine(number);
}
Safe and readable. Combines type check and casting.
dynamic dyn = GetObject();
int x = dyn + 10;
Evaluates at runtime. Very flexible but can throw runtime exceptions if used carelessly.
Convert
Classstring input = "42";
int x = Convert.ToInt32(input);
Best for converting between strings, numbers, etc. May throw FormatException
or OverflowException
.
Learn all these techniques in detail with real-world examples in my full video:
I offer personalized 1-on-1 training in:
Call or WhatsApp: +91-9331897923
Visit: http://supernovaservices.com