none
Cast a null object to string RRS feed

  • General discussion

  •  why there is no error raised when I cast a null object to string?

    object o = null;

    string s = (string)o; //No error is raised Why?


    Thanks, Ankita

    Monday, October 8, 2012 7:44 AM

All replies

  • Because null is a valid value for string and string is an object.

    SomeClass test = null;
    string s = (string)test;

    The above will not work because string is not SomeClass, but the below will work as both SomeClass and string are object.

    SomeClass test = null;
    object o = test;
    string s = (string)o;



    Monday, October 8, 2012 7:53 AM
    Moderator
  • Hi,

    because a string can be null. (Test also with commenting out the second line)

                string f = null;
                f += "afl";
                MessageBox.Show(f);

    and therefore you can cast o to type string without error.

    But you cannot call any methods on o like ToString() since it is null and therefore no instance:

                object o = null;
                string s = o.ToString(); //error

    Regards,

      Thorsten



    Monday, October 8, 2012 7:55 AM
  • Yeah right. Thanks Andreas  and Thorsten !


    Thanks, Ankita

    Monday, October 8, 2012 8:38 AM