Do "generic" objects know what types they contain?

  • Thread starter Thread starter Tom H.
  • Start date Start date
T

Tom H.

Newbie question, hopefully not one that will embarrass me.

I'm reading Richter's Applied MS .NET Framework Programming and keep
seeing snippets such as this:

Int32 v = 5;
Object o = v;
Console.Writeline("{0}, {1}, {2}", o, o, o);

in which it appears that code referencing an Object magically knows
the type of data it contains. Is the type stored in the object
itself, or is it determined by some set of rules?
 
Tom H. said:
Int32 v = 5;
Object o = v;
Console.Writeline("{0}, {1}, {2}", o, o, o);
[...]
Is the type stored in the object itself, or is it determined
by some set of rules?

Int32 inherits from Object, so its overridden version of ToString is
used for output.

P.
 
All objects in C# inherit from the base class System.Object. System.Object
provides a GetType() method so you can always find out exactly what type of
object is being held by a System.Object.
System.Object also provides a ToString() method which is what is being
called by WriteLine, but since the object is really an Int32,
Int32.ToString() is called instead of Object.ToString().
 
Yes each object knows its actual type:

Int32 v = 5;
Object o = v;
Console.Writeline(o.GetType());

Will print System.Int32. This is because '5' is converted into a regular
object before it is stored into o.
 
Back
Top