In this example following way casting is done. string value = list[i] as string;
Similar output is obtained with varied casting way string value = (string)list[i];
My question is whether casting is correct either way whatever data types are.
using System;
using System.Collections;
class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add("man");
list.Add("woman");
list.Add("plant");
for (int i = 0; i < list.Count; i++)
{
string value = list[i] as string;
Console.WriteLine(value);
}
Console.ReadKey();
}
}
Loading
VulpesPosted Jul 8, 2013, 5:03 AM
It doesn't work with non-nullable value type conversions or with user-defined conversions for which you must use a cast instead.
The following program illustrates these points:
Posted Jul 8, 2013, 6:42 AM
Iftikar HussainPosted Jul 8, 2013, 12:06 AM
The difference between below two type casting is
string value = list[i] as string; - This is Safe Casting
string value = (string)list[i]; - This is a normal Casting
The Safe Casting will not throw you InvalidCastException, instead it will return you null if the cast fails. Where as normal Casting will throw you the InvalidCastException error
So you need to use Safe Casting when you are not sure about the desired casting type else you can use normal Casting.
In your example just modify your code and check
By Using Safe Casting
using System;
using System.Collections;
class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add(new Object());
list.Add("woman");
list.Add("plant");
for (int i = 0; i < list.Count; i++)
{
string value = list[i] as string;
Console.WriteLine(value);
}
Console.ReadKey();
}
}
The output will be
(null)
woman
plant
By Using normal Casting
using System;
using System.Collections;
class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add("man");
list.Add("woman");
list.Add("plant");
for (int i = 0; i < list.Count; i++)
{
string value =(string) list[i];
Console.WriteLine(value);
}
Console.ReadKey();
}
}
The output
It will throw InvalidcastException
Regards,
Iftikar
Jignesh TrivediPosted Jul 7, 2013, 10:57 PM
As per my knowledge, when you cast using (string)list[i] it forcing compiler to cast it gave runtime exception if cast type is not match.
when you cast using "as" keyword it try cast object, if object is not cast to target type then it return null value or default value. it means, if the conversion isn't possible, as returns null instead of raising an exception. internally perform following operation.
expression is type ? (type)expression : (type)null
hope this will help you.