Is and as operators are used to casting similar/compatable types only.and casting is done as per the holding value also.
but the scenerious are different.
IS
but the scenerious are different.
IS
is operator is used to casting between 2 compatable types.
which create an expression, and returns a Boolean value.
isDemo:
string str = "propercode";
object obj = "20";
if (str is object)
{
Console.WriteLine("casting is possible");
}
if (str is StringBuilder)
{
Console.WriteLine(" casting not possible b/w string and sbuilder");
}
else
{
Console.WriteLine("both are incompatable types");
}
if (obj is string)
{
Console.WriteLine("casting is possible "); //----"20"
}
else
{
Console.WriteLine("casting is not possible");//----20
}
In case of obj holding value as string type then compatable is possible.if
In case of obj holding value as integer type then compatable is not possible.else
AS:
as operator is used to casting between 2 compatable types.
which doesn’t return any Boolean value.
object obj = "20";
string str2 = obj as string;
Console.WriteLine(str2.GetType());
obj holds value as string so compatable is possible. incase of storing as integer error.
string str = "propercode";
object objs = str as object;
Console.WriteLine(objs.GetType());
Difference between typeof operator and GetType() Method?
Typeof(classname) operator
Type t = typeof(string);
Console.WriteLine(t);
Type t1 = typeof(Employee);
Console.WriteLine(t1);
Typeof operator excepts classname to know the underlying type.
GetType() Method
Type t1 = typeof(Employee);
Console.WriteLine(t1);
//or
Employee eobj = new Employee();
Console.WriteLine(eobj.GetType());
Requeries instance to know the underlying type.
default operator
StringBuilder variable1 = default(StringBuilder);
int variable2 = default(int);
bool variable3 = default(bool);
Program variable4 = default(Program);
string s = default(string);
// Write the values.
Console.WriteLine(variable1); // Null
Console.WriteLine(variable2); // 0
Console.WriteLine(variable3); // False
Console.WriteLine(variable4); // Null
Console.WriteLine(s);
No comments:
Post a Comment