5
Answers

As casting

Maha

Maha

11y
965
1
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

Answers (5)