Hi Guys
NP79 Base Type & ToString()
Out put of Console.WriteLine(o.GetType()); is System.Int32, when BaseType added that means out put of Console.WriteLine(o.GetType().BaseType); is System.ValueType. Please explain the reason.
ToString() Returns a string representation of a given object, using the namespace.class name. But here ToString() Returns 99 that means Console.WriteLine(o.ToString()); is giving an out put 99. Please explain the reason.
Also explain GetTypeCode() as well.
Thank you
using System;
class Boxer
{
// Helper f(x) to illustrate automatic boxing.
public static void UseThisObject(object o)
{
Console.WriteLine(o.GetType());
Console.WriteLine(o.GetType().BaseType);
Console.WriteLine(o.ToString());
Console.WriteLine("Value of o is: {0}", o);
// Need to explicitly unbox to get at members of
// System.Int32. (GetTypeCode() returns a value
// representing the underlying “type of intrinsic type”.
Console.WriteLine(((int)o).GetTypeCode());
}
static void
{
int x = 99;
UseThisObject(x); // Automatic boxing.
}
}
/*
System.Int32
System.ValueType
99
Value of o is: 99
Int32
*/
Posted Feb 5, 2008, 3:10 PM
Thank you for your help, Alan.
AlanPosted Feb 5, 2008, 7:49 AM
The Object.GetType() method returns the runtime type of the object it is applied to.
Thus, when the UseThisObject() method's parameter 'o' is passed an int, o.GetType() returns a type of System.Int32 to give int its full title.
Now all value types such as int inherit from a class called System.ValueType and so this is the type which o.GetType().BaseType() returns.
object.ToString() is a virtual method which means that all derived types can either simply inherit it or override it with their own implementation. If they don't override it then a string representation of the type name is returned.
However, the System.Int32 type does override it and returns a string representation of the numerical value of the object, which in this case is "99".
The Int32.GetTypeCode() always returns a value of TypeCode.Int32 where TypeCode is an enum which has different values for various types. When Comsole.WriteLine() is applied to this value, the enum.ToString() method is implicitly called and returns a string representation of "Int32".