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

VulpesRank #55 · 29.2K reputationPosted Oct 23, 2013, 7:24 AM EDT
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.
Posted Oct 23, 2013, 11:25 AM EDT
Posted Oct 27, 2013, 1:49 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 27, 2013, 5:05 AM EDT
However, there's no inheritance relationship between the two types which is why a cast doesn't work.
Posted Oct 27, 2013, 5:24 AM EDT