none
Doubt on typeof function. RRS feed

  • Question

  • Hi,

    I have one doubt regarding typeof method. Check the following example.

    var type =  typeof(Enumerable);

    Now type variable should becomes type of Enumerable class. When i see properties of type in quick watch i am getting object of System.RuntimeType who has two value i.e. Name = "Enumerable", FullName = "System.Linq.Enumerable"

    Now if i do following part

    string str = type + "mystring";

    It works well.

    Doubt: How a string "mystring" is simply added to type object whose base type is System.RuntimeType?

    What is happening behind the scene?

    Monday, July 9, 2012 7:09 AM

Answers

  • That is a feature of string concatenation. When you do type + "myString" and both type & "mystring" are of different types, compiler will do string concatenation. Hence, it will call ToString() on type. So, that code becomes,

    string str = type.ToString() + "mystring";

    This becomes,

    string str = "System.Linq.Enumerable" + "mystring";

    So, finally str containes "System.Linq.Enumerablemystring"

    I hope this helps.


    Please mark this post as answer if it solved your problem. Happy Programming!

    • Marked as answer by Gopal.sml Monday, July 9, 2012 6:34 PM
    Monday, July 9, 2012 8:42 AM

All replies

  • Hi,

    If you write var type= typeof(int); or var type=typeof(double); or var type =typeof(string); or var type =typeof(char); and then write Console.WriteLine("{0}",type.GetType()); ,then for all of the cases, you'll always get System.Runtime as the type because its type is being declared on runtime.

    But now do one thing, Write double type=2.8; Console.WriteLine("{0}", type.GetType()); You'll see that the output will be System.Double. Or Write int type=3; Console.WriteLine("{0}", type.GetType()); You'll see that the output will be System.Int32. This is because you have declared the type explicitly and the type is not being declared on the run time.

    I hope this might help you.

    Thanks

    Monday, July 9, 2012 8:22 AM
  • That is a feature of string concatenation. When you do type + "myString" and both type & "mystring" are of different types, compiler will do string concatenation. Hence, it will call ToString() on type. So, that code becomes,

    string str = type.ToString() + "mystring";

    This becomes,

    string str = "System.Linq.Enumerable" + "mystring";

    So, finally str containes "System.Linq.Enumerablemystring"

    I hope this helps.


    Please mark this post as answer if it solved your problem. Happy Programming!

    • Marked as answer by Gopal.sml Monday, July 9, 2012 6:34 PM
    Monday, July 9, 2012 8:42 AM