Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# value type and String

This is a homework question, which is why it might be somewhat odd(also apologize if the title isn't very good)

Assuming that v1 is a value type of type X that redefines ToString, is there any difference between using Console.WriteLine(v1) and Console.WriteLine(v1.toString())?

like image 909
Andreia Alexandra Avatar asked Dec 17 '22 00:12

Andreia Alexandra


1 Answers

The simplest answer is that "yes, there's a difference". Obviously the important thing is that you know what that difference is though. I won't tell you that, but I'll tell you how to investigate it...

  • Write a short program which contains a custom value type as described, and both Console.WriteLine(v1) and Console.WriteLine(v1.ToString()) in a Main method
  • Compile the program
  • Run ildasm (or Reflector in IL mode) and look at the difference between the method invocations
    • Which method overload is invoked in each case?
    • What happens to the value in each case?

Questions which you might want to think about and which might get you extra credit:

  • Is there any difference if you use a custom class instead of a struct?
  • Can you think of any way that Console.WriteLine could have been designed which would have removed any inefficiency you've noticed?
like image 88
Jon Skeet Avatar answered Dec 30 '22 09:12

Jon Skeet