473,785 Members | 2,575 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why doesn't the compiler use ToString for implicit conversions?

Maybe I'm missing some fundamental unwritten law of OOP, but I was
wondering why the VB.NET compiler doesn't take advantage of the fact
that all .NET objects, being derived from the Object base class, have
a ToString method defined on them, when a reference type is used in an
expression where a String is expected. I mean if you define a class
MyClass in MyNamespace and don't override ToString, calling ToString
will return the qualified type name: "MyNamespace.My Class" (the
default behavior). If you then do this:

Dim myObject As MyNamespace.MyC lass
Dim str As String

str = "MyClass converted to a string = " & myObject

The compiler will complain that myObject cannot be cast to String. The
compiler obviously knows what types are involved in any potential
conversion, so why can't it just call myObject.ToStri ng to perform the
conversion on realizing that myObject should be converted to String?
In another OOP language this might not make sense, since the compiler
can't assume a method called ToString exists on any given object, but
since .NET objects by definiton must all inherit from the common
Object base class, and ToString is part of Object's defintion, why
shouldn't the compiler just call ToString, since it knows the method
will be there?

Now, obviously, you can easily get around all this by explicitly
calling ToString yourself, but I'm wondering why the compiler won't
simply do it automatically (perhaps it could perform it only as long
if Option Strict is Off to give the programmer a choice).

I mean, the compiler will implicitly convert a value type into a
String when necessary, why not extend this to reference types in the
specific case of converting to String, since, again, the ToString is
readily available?

I guess what I'm getting at is this: is there a good reason why it
doesn't work this way? Especially when you consider that the following
code works without needing to explicitly call myObject.ToStri ng:

Console.WriteLi ne(myObject)

I assume this works because the parameters to WriteLine are of type
Object, and my guess is that WriteLine simply calls ToString on the
objects passed to it to get a String suitable for output. So, it's
more to do with how WriteLine is implemented rather than a situtation
where a compiler-defined conversion occurs, but what's stopping the
compiler from doing the same thing in the specific case of converting
a reference type to String?

--
Mike

Apr 27 '07 #1
3 1958
I don't know the right reasons for that. But one of them might be the
fact that you can redefine ToString so that it doesn't return string:

Class MyClass
''' <summary>Craz y ToString.</summary>
Public Shadows Function ToString() As Collection
Return New Collection
End Function
End Class

And I think the "Shadows" keyword is not even necessary here.
--
Peter Macej
Helixoft - http://www.helixoft.com
VSdocman - Commenter and generator of class documentation for C#, VB
..NET and ASP .NET code
Apr 27 '07 #2
>I don't know the right reasons for that. But one of them might be the
fact that you can redefine ToString so that it doesn't return string:
But you (and the compiler) can still call the base definition.

C# supports this so its definitely doable.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Apr 27 '07 #3
By requiring the use of the ToString() method in code, the VB 2005 compiler
eliminates an entire class of possible bugs caused by incorrect type
casting. Yes, C# can do this, but IMO doing so leads to harder to read
code.

Mike Ober.
"Mattias Sjögren" <ma************ ********@mvps.o rgwrote in message
news:uL******** ******@TK2MSFTN GP02.phx.gbl...
>
>>I don't know the right reasons for that. But one of them might be the
fact that you can redefine ToString so that it doesn't return string:

But you (and the compiler) can still call the base definition.

C# supports this so its definitely doable.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Apr 28 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
1871
by: Neil Zanella | last post by:
Hello, I wonder whether anyone has ever come across the following g++ compiler error message. I don't recall ever seeing it before. I solved my problem but I am still not sure about what this message is all about. Any ideas? error: invalid initialization of non-const reference of
15
2301
by: buda | last post by:
Let me see if I got this :) 1. I know the rules for type conversions in arithmetic expressions 2. I know that an implicit type conversion is done at assignment, so float x = 1.23; int t = (int) x; is equivalent to int t = x; (could the latter produce a warning on some complier?) 3. I know that implicit conversions take place with function arguments, but am a bit shaky here. I suppose that passing a char to a function accepting
5
2065
by: Wilfried Mestdagh | last post by:
Hi, I have a class that holds data in array of byte. It has property to get the data like this (FBuffer is a byte): public byte Data { get { return FBuffer; } }
3
1368
by: Rudy | last post by:
I am writing a program in VB.NET and as I was debugging a problem I noticed my For loop doesn't want to loop! I originally had a upper bound which was an expression and it wasn't working. WHen I noticed this I changed the upper bound for a simple digit. As I step through my code, I see that it simply goes through the loop once and continues on it's merry way. Now I have programmed in Java, C++, and even Modula 3 before and I have never seen...
36
3636
by: Chad Z. Hower aka Kudzu | last post by:
I have an implicit conversion set up in an assembly from a Stream to something else. In C#, it works. In VB it does not. Does VB support implicit conversions? And if so any idea why it would work in a C# program but not VB? -- Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/ "Programming is an art form that fights back"
6
1393
by: =?Utf-8?B?RGF2ZQ==?= | last post by:
I found a really strange quirk in the C# compiler, which I can't beleive is proper behaviour. If I define a class thus: public class MyClass { public override string ToString() { return base.ToString(); } }
31
6172
by: Zytan | last post by:
Everything (er, every class) in C# has ToString() which is conveniently automatically invoked when using it in Debug.WriteLine() or in a string concatenation, etc. I made a struct, and I want to make a method to print out its data in a similar format. So, I did this: public struct MyStruct { public override string ToString() {
15
2036
by: Jason Doucette | last post by:
If you have two overloaded functions: double maximum(double a, double b, double c); int maximum(int a, int b, int c); They work fine if you call maximum() with all arguments as doubles, or all as ints. But, if you mix up doubles with ints in the argument list, it doesn't know which maximum() to call... but only one could possibly match -- the one that takes doubles.
35
2916
by: =?Utf-8?B?UElFQkFMRA==?= | last post by:
I'd really like to be able to constrain a generic type to System.Enum or, better, enum. But of course that results in "Compiler Error CS0702". So far I've been checking the type parameter at runtime and throwing an exception if the provided type is not an enum. That works, but it just doesn't seem quite right. After reading through section 4.4.4 of the C# 3.0 spec I see no reason why constraining to System.Enum should not be allowed.
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10148
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.