tags:

views:

122

answers:

1
 object nullobject = null;
 object myobject = new myobject();
 console.writeline("nullobject="+nullobject+"myobject="+myobject);
+3  A: 

It (unexpectedly for me, anyway) prints

nullobject=myobject=System.Object

(changing your = new myobject(); line to = new object(); and correcting other typos.)

The thing I didn't know (and the reason I'm bothering to post this) is CSharp treats null string objects as empty strings when concatenating. There's a note halfway down this page about it. http://msdn.microsoft.com/en-us/library/ms228504.aspx

object nullobject = null;
object myobject = new object();
Console.WriteLine(nullobject + "");         //ok, prints empty line
Console.WriteLine(nullobject.ToString());   //this will blow up
Console.WriteLine("nullobject=" + nullobject + "myobject=" + myobject); //ok, prints what's above.
Tim Coker
Thank you for your answer and correcting my typos (sorry about that)but what i really wanted to ask here was that what does an object of class Object in C# print when null is assigned to it andIn the second line Object myobject = new myobject();what will be printed now if i try to print myobject.
Mohsin Sheikh Khalid
When you call `Console.WriteLine(obj)` or `string.Format("{0}", obj)`, `obj`'s `ToString()` method will get called. (The interesting point I wasn't aware of is csharp will use an empty string in place of a null object for most string operations, except for direct calls to `ToString()`). `ToString()` is an overridable method in the `object` type. Since everything in csharp inherits from `object`, any of your classes can override this and return any text you want. By default, you will get the name of their type, IE, `System.Object`, above.
Tim Coker