What is the different between as casting and usual casting. Because this program is executing with usual casting, when it is done on string data type but with StringBuilder data type program is not executing with usual casting. Please explain the reason. This program is given in the following website. Problem is highlighted.
http://www.dotnetperls.com/as
using System;
using System.Text;
class Program
{
static void Main()
{
// Create a string variable and cast it to an object.
string variable1 = "carrot";
object variable2 = variable1;
// Try to cast it to a string.
//string variable3 = variable2 as string;
string variable3 = (string)variable2;
if (variable3 != null)
{
Console.WriteLine("have string variable");//have string variable
}
// Try to cast it to a StringBuilder.
//StringBuilder variable4 = variable2 as StringBuilder;
StringBuilder variable4 = (StringBuilder)variable2;
if (variable4 != null)
{
Console.WriteLine("have StringBuilder variable");
}
Console.Read();
}
}
//have string variable
Loading
Posted Oct 27, 2013, 9:24 AM
VulpesPosted Oct 27, 2013, 9:05 AM
However, there's no inheritance relationship between the two types which is why a cast doesn't work.
Posted Oct 27, 2013, 5:49 AM
Posted Oct 23, 2013, 3:25 PM
VulpesPosted Oct 23, 2013, 11:24 AM
If you think beforehand that the conversion might fail (the types may be incompatible), then you can use 'as' rather than a cast to make the conversion. If the conversion fails, then 'as' returns null rather than throwing an exception. Otherwise it works the same as a cast.
However, there are some restrictions on the use of 'as':
1. It only works with reference type or nullable type conversions, not value type conversions.
2. It can't be used for user-defined conversions.
The reason a normal cast doesn't work here is because you can't cast a string to a StringBuilder.