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

Home Posts Topics Members FAQ

Is this really correct compiler behaviour

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() ;
}
}

and then call it thus:

MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.
--
Dave
Feb 22 '07 #1
6 1393
On Feb 22, 7:24 am, Dave <D...@discussio ns.microsoft.co mwrote:
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() ;
}
}

and then call it thus:

MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.
--
Dave
Hi Dave,
Yes I think it makes sense. I think you might have wanted to say
"string test1 = myClass.ToStrin g();" instead of "string test1 =
myClass;". The compiler won't do the implicit conversion for you.
Even if you've overridden ToString() it won't do this conversion --
all objects have a default ToString() implementation so the fact that
you've overridden the function doesn't really change anything,

In the case where you append an empty string, the + operator causes
the compiler to check to see if myClass can be converted to a string.

John

Feb 22 '07 #2
Dave wrote:
I found a really strange quirk in the C# compiler, which I can't beleive is
proper behaviour.
It's by design.
MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.
Imagine that there's two versions of the '+' operator defined on
System.String, thusly:

public static string operator +(string left, object right);
public static string operator +(object left, string right);

(There isn't, because much string stuff is built-in.)

What you're expecting amounts to something more like this, defined on
System.Object:

public static implicit operator string(object value);

I think it's a compromise between the usefulness of having string
representations of objects, versus the downside of having objects turn
into strings at the drop of a hat. Implicit conversions that lose
information are usually considered to be a bad idea; at least the '+'
operator requires that you have an expression of string type on the left
or right beforehand.

-- Barry

--
http://barrkel.blogspot.com/
Feb 22 '07 #3
Of course the correct thing to do is to use ToString() explicitly, my example
is to illustrate the odd behaviour which does seem to be extremely
inconsistant. I mean either myClass can be implicitly converted to a string
or it can't, it shouldn't depend on the context like this surely (it
certainly wouldn't in C++).
--
Dave
"John Duval" wrote:
On Feb 22, 7:24 am, Dave <D...@discussio ns.microsoft.co mwrote:
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() ;
}
}

and then call it thus:

MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.
--
Dave

Hi Dave,
Yes I think it makes sense. I think you might have wanted to say
"string test1 = myClass.ToStrin g();" instead of "string test1 =
myClass;". The compiler won't do the implicit conversion for you.
Even if you've overridden ToString() it won't do this conversion --
all objects have a default ToString() implementation so the fact that
you've overridden the function doesn't really change anything,

In the case where you append an empty string, the + operator causes
the compiler to check to see if myClass can be converted to a string.

John

Feb 22 '07 #4
On Thu, 22 Feb 2007 04:24:02 -0800, Dave
<Da**@discussio ns.microsoft.co mwrote:
>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() ;
}
}

and then call it thus:

MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.
If one of its operands is a string then the concatenation '+' operator
will look for either an implicit type conversion or ToString() if the
other operand is not a string.

The assignment operator '=' only looks for built in or 'implicit' type
conversions, it does not look for ToString().

If you want your assignment to work as written then define an implicit
type conversion:

implicit operator string(MyClass mc) { return mc.ToString(); }

The assignment operator will recognise this implicit type conversion.

rossum

Feb 22 '07 #5
Actually I don't want the assignment to work as written, quite the opposite.
This arose because of some code of mine that compiled without error - it was
only when I removed the concatenated string that it suddenly produced
compiler errors and I realised that I had unknowingly used completely the
wrong variable. I would actually expect both of the statements in my example
to fail to compile.
--
Dave
"rossum" wrote:
On Thu, 22 Feb 2007 04:24:02 -0800, Dave
<Da**@discussio ns.microsoft.co mwrote:
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() ;
}
}

and then call it thus:

MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.

If one of its operands is a string then the concatenation '+' operator
will look for either an implicit type conversion or ToString() if the
other operand is not a string.

The assignment operator '=' only looks for built in or 'implicit' type
conversions, it does not look for ToString().

If you want your assignment to work as written then define an implicit
type conversion:

implicit operator string(MyClass mc) { return mc.ToString(); }

The assignment operator will recognise this implicit type conversion.

rossum

Feb 22 '07 #6
Dave <Da**@discussio ns.microsoft.co mwrote:
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() ;
}
}

and then call it thus:

MyClass myClass = new MyClass();
string test1 = myClass;

it does not compile, because it cannot implicitly convert myClass to a string.
But if I call it thus:

MyClass myClass = new MyClass();
string test1 = myClass + "";

it compiles fine. I'd be interested to know if anyone thinks that makes sense.
From http://www.jaggersoft.com/csharp_standard/14.7.4.htm

<quote>
The binary + operator performs string concatenation when one or both
operands are of type string. If an operand of string concatenation is
null, an empty string is substituted. Otherwise, any non-string
argument is converted to its string representation by invoking the
virtual ToString method inherited from type object. If ToString returns
null, an empty string is substituted.
</quote>

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 22 '07 #7

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

Similar topics

6
1576
by: jon morgan | last post by:
Hi, I get random errors raised when compiling a multi-project application. For example the compiler will claim that a class has no constructor when it does. If I replace the first line of the constructor with the same code ( or just re-load VS) and then recompile things are OK for a while but then the spurious error comes back. The same sort of random behaviour can occur anywhere in my app. - basically the compiler doesn't "see" a line...
11
2379
by: Mantorok Redgormor | last post by:
Is const really constant? And on an OT note: how can I post with a modified e-mail address so I don't get so much spam?
6
3489
by: Rob Thorpe | last post by:
Given the code:- r = sscanf (s, "%lf", x); What is the correct output if the string s is simply "-" ? If "-" is considered the beginning of a number, that has been cut-short then the correct output is that r = EOF. If it is taken to be a letter in the stream, then the output should be r = 0, as far as I can see. My compiler gives EOF.
29
2528
by: junky_fellow | last post by:
Consider the following piece of code: struct junk { int i_val; int i_val1; char c_val; }; int main(void) {
24
1842
by: temper3243 | last post by:
Hi, Many people have used this code in my project. It works because b is using the extra memory for other 4 variables.I access obj max. well here are a few questions 1) Where does it fail. I mean is there any exception where it willnot work assuming malloc works fine. 2) someone told me in C99 we have declar b obj , so that it can be declared at runtime. How do we do that. Do we have to malloc again .
29
1876
by: Rohit kumar Chandel | last post by:
Hi all, I have a doubt in const keyword. My understanding says that a variable declared const can not be modified by the module it is defined in. Then consider the following code segment: main() { const int p =5; int* pp = &p; ++(*pp);
14
2174
by: jeniffer | last post by:
Hi I want to know why is a = i++ ; wrong? People say that it is because of different parsing during compilation.Please explain technically why it is wrong/behaviour undefined? Regards, Jeniffer
6
1844
by: jt | last post by:
#include <stdio.h> void f(); int main() { long int i; i=20; f(); i = 10; printf ("\n%d\n",i);
17
5820
by: Chris M. Thomasson | last post by:
I use the following technique in all of my C++ projects; here is the example code with error checking omitted for brevity: _________________________________________________________________ /* Simple Thread Object ______________________________________________________________*/ #include <pthread.h> extern "C" void* thread_entry(void*);
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,...
1
10092
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
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3647
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.