473,804 Members | 3,271 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct ToString() not automatically invoked

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()
{
return ("Hello");
}
}

But, it doesn't get automatically invoked. It complains if I don't
put "public" or "override", so I assume it knows that it's overriding
something (I am not sure what, since it's not a class, and thus not an
object). So:
1. why does it complain without "override"? and
2. why isn't it automatically invoked?

I know classes are references and structs are value types. Since the
struct isn't a class, I don't even know *why* it is complaining about
my creation of a ToString() method in it. I would expect it wouldn't
complain, and also wouldn't be invoked automatically. But, since it
does complain surprisingly, I thought maybe it would also be invoked
automatically, which it doesn't.

Zytan

Mar 7 '07
31 6174
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************** *@msnews.micros oft.com...
Bill Butler <qw****@asdf.co mwrote:
>"Zytan" <zy**********@y ahoo.comwrote in message
news:11******* *************** @8g2000cwh.goog legroups.com...
<snip>
(And, this begs the question: Why are the other [single parameter]
WriteLine overloads even needed, if you have WriteLine(objec t)?)

Efficiency. That is the same reason it has
Writeline(strin g format, obj1);
Writeline(strin g format, obj1, obj2);
Writeline(strin g format, obj1, obj2, obj3);

when
Writeline(strin g format, params object[] objs);
would have sufficed. These overrides perform better.

No, that's not for efficiency - it's to help those languages which
don't support "params" parameters automatically. Internally the
overloads which don't take an array create an array anyway.
Thanks for the info.

Bill
Mar 9 '07 #21
(And, this begs the question: Why are the other [single parameter]
WriteLine overloads even needed, if you have WriteLine(objec t)?)

Efficiency. That is the same reason it has
Writeline(strin g format, obj1);
Writeline(strin g format, obj1, obj2);
Writeline(strin g format, obj1, obj2, obj3);

when
Writeline(strin g format, params object[] objs);
would have sufficed. These overrides perform better.
Right.
Right, I could mimic Console.WriteLi ne. Well, my function is for
logging, so perhaps I should just use the Print(object) style, and let
it call the ToString() on anything I pass in. Isn't that good enough
to cover basic Console.WriteLi ne (the single parameter overloads)
functionality?

It would work. You have to decide if it is "Good enough".
Yes, it is. Thanks, Bill

Zytan

Mar 12 '07 #22
(Although, when you concatenate strings, it does invoke ToString()
automatically, so it seems to be implicitly converting anything into a
string as it wishes, so that's strange.)

String concatenation is an exception (which is part of the C# language,
by the way, not something done automatically by .NET) which is just for
sake of convenience. Sometimes purity comes second to practicality :)
Ah, ok. Yes, and I think everyone's happy with this.

Zytan

Mar 12 '07 #23
Zytan wrote:
>So you are presuming there is an implicit *conversion* going on here when in
fact I don't think there is.

Yes! And I think this arose from the fact that concantenating strings
implicitly invokes ToString(), and I may even have read somewhere (or
maybe just thought it myself) that the same thing happens when using
Debug.WriteLine or Console.WriteLi ne.
The same thing actually happens, and it's not an implicit conversion in
either case.

If you concatenate two strings, the string.Concat(s tring, string) method
is used. But if you are concatenating a string with something else, the
string.Concat(o bject, object) method is used. The ToString method is
called, but not before the values is sent to the Concat method, but
inside the Concat method.

There is something that is done implicitly if you are using a value type
in this way, though, and that is boxing. As the method takes the type
object, a new object has to be created that contains the value from the
value type.

So the expression "foo" + bar where bar is a value type is equivalent to
"foo" + new object(bar). (Not that the object constructor takes
parameters, but you get the idea.)

--
Göran Andersson
_____
http://www.guffa.com
Mar 12 '07 #24
On Mar 7, 3:06 pm, "Zytan" <zytanlith...@y ahoo.comwrote:
No, it doesn't - and it doesn't for classes either, thankfully.

Why thankfully?
Why did you expect that it would?

It does for Console.WriteLi ne which takes a string.
Why not for MyOwnFunction which takes a string?
I see no difference between the two.

(I personally was surprised that C# does this at all implicitly, since
it does so much to ensure proper / strict type checking, so I don't
care that I must do astruct.ToStrin g() manually.)
You could add your own implicit conversion to a string, although I
wouldn't recommend it.

Ok, I don't think you mean using Print(astruct.T oString()), so you
must mean adding such capability to the struct itself, such that I can
do Print(astruct). I'd prefer not to do that anyway. But, why is it
needed? And why is it not recommended?
Just to clear up the final mystery in this thread, an "implicit
conversion" is a static method that you can write as part of your
class or struct that tells the compiler that your type can silently be
converted to some other type.

An example may help. I have written a Fraction struct. It allows me to
represent rational numbers (the company I work for is in the wood
business, so we often have to deal with values like "15 7 / 32" or
"1 / 2"). I have an implicit conversion from Fraction to decimal. This
means that I can do this:

Fraction half = new Fraction(1, 2);
decimal d = half;

On that second line, the compiler invokes my implicit conversion
function to convert the Fraction to a decimal.

You can also write explicit conversions: conversions that require the
programmer to specify an explicit cast. If I had written the Fraction-
to-decimal conversion as explicit, I would be forced to do this:

Fraction half = new Fraction(1, 2);
decimal d = (decimal)half;

You can read more here:

http://msdn2.microsoft.com/en-us/lib...0a(VS.80).aspx

Conversions (explicit and implicit) and operator overloading are best
used sparingly, as they can be horribly abused (as they can be in C++,
too). I tend to restrict mine to structs (value types) and then only
in situations in which (I believe) it will be abundantly clear to the
reader of the code what is going on.

As a counterexample, this:

WarehouseDetail warehouseInfo =
stockItem.GetWa rehouseDetail(w arehouse);

is much easier to understand than this:

WarehouseDetail warehouseInfo = stockItem + warehouse;

although the latter is simple to achieve with an operator overload.

Mar 12 '07 #25
Jon Skeet [C# MVP] wrote:
Zytan <zy**********@y ahoo.comwrote

<snip>
>(Although, when you concatenate strings, it does invoke ToString()
automaticall y, so it seems to be implicitly converting anything into a
string as it wishes, so that's strange.)

String concatenation is an exception (which is part of the C# language,
by the way, not something done automatically by .NET) which is just for
sake of convenience. Sometimes purity comes second to practicality :)
Actually it's not an exception at all. The same thing happens as with
the WriteLine method; there is an overload that take object parameters.

When you concatenate two strings, the string.Concat(s tring, string)
method is used, but when you are concatenating a string with something
else, the string.Concat(o bject, object) method is used. The ToString
method is used, but not implicitly before the value is used, but inside
the Concat method.

--
Göran Andersson
_____
http://www.guffa.com
Mar 12 '07 #26
Göran Andersson <gu***@guffa.co mwrote:
(Although, when you concatenate strings, it does invoke ToString()
automatically, so it seems to be implicitly converting anything into a
string as it wishes, so that's strange.)
String concatenation is an exception (which is part of the C# language,
by the way, not something done automatically by .NET) which is just for
sake of convenience. Sometimes purity comes second to practicality :)
Actually it's not an exception at all. The same thing happens as with
the WriteLine method; there is an overload that take object parameters.
Well, I'd still say that it *is* an exception. At the *language* level
it appears to be an overloaded operator, but it actually isn't.

The underlying calls are irrelevant to the fact that it's a
specifically defined operator in C#, whereas WriteLine certainly isn't!

The string.Concat method isn't the exception here, it's the fact that
it's called when you do "foo" + x that is the exception.

I think I see what you're getting at though - it's not the C# compiler
that's calling ToString(), it's string.Concat. I certainly agree on
that point. But the context of my post was that Zytan expected ToString
to be called to allow any object to be passed to a method with a string
parameter, because he'd seen the string concatenation operator.

--
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
Mar 12 '07 #27
Jon Skeet [C# MVP] wrote:
Göran Andersson <gu***@guffa.co mwrote:
>>>(Although, when you concatenate strings, it does invoke ToString()
automaticall y, so it seems to be implicitly converting anything into a
string as it wishes, so that's strange.)
String concatenation is an exception (which is part of the C# language,
by the way, not something done automatically by .NET) which is just for
sake of convenience. Sometimes purity comes second to practicality :)
Actually it's not an exception at all. The same thing happens as with
the WriteLine method; there is an overload that take object parameters.

Well, I'd still say that it *is* an exception. At the *language* level
it appears to be an overloaded operator, but it actually isn't.

The underlying calls are irrelevant to the fact that it's a
specifically defined operator in C#, whereas WriteLine certainly isn't!

The string.Concat method isn't the exception here, it's the fact that
it's called when you do "foo" + x that is the exception.
Yes, the fact that the compiler implements the concatenation operator
with the Concat method is an exception. But once you are past that it
all follows the pattern. There is no magic conversions added by the
compiler.
I think I see what you're getting at though - it's not the C# compiler
that's calling ToString(), it's string.Concat. I certainly agree on
that point. But the context of my post was that Zytan expected ToString
to be called to allow any object to be passed to a method with a string
parameter, because he'd seen the string concatenation operator.
Yes, and my point was that if you realise what the concatenation
operator really does, you see that there is no conversions added to the
code.

When you see that the compiler doesn't add any ToString calls in that
case, you won't expect it to do that anywhere else.

--
Göran Andersson
_____
http://www.guffa.com
Mar 12 '07 #28
When you concatenate two strings, the string.Concat(s tring, string)
method is used, but when you are concatenating a string with something
else, the string.Concat(o bject, object) method is used. The ToString
method is used, but not implicitly before the value is used, but inside
the Concat method.
Thanks for the details, Göran, it's easier to follow what's happening
when you know them.

Zytan

Mar 13 '07 #29
I think I see what you're getting at though - it's not the C# compiler
that's calling ToString(), it's string.Concat. I certainly agree on
that point. But the context of my post was that Zytan expected ToString
to be called to allow any object to be passed to a method with a string
parameter, because he'd seen the string concatenation operator.
Yes, I did.
Yes, and my point was that if you realise what the concatenation
operator really does, you see that there is no conversions added to the
code.

When you see that the compiler doesn't add any ToString calls in that
case, you won't expect it to do that anywhere else.
Right. Thanks for the help, guys.

Zytan

Mar 13 '07 #30

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

Similar topics

18
3055
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
20
2980
by: fix | last post by:
Hi all, I feel unclear about what my code is doing, although it works but I am not sure if there is any possible bug, please help me to verify it. This is a trie node (just similar to tree nodes) struct, I am storing an array of 27 pointers and a void pointer that can point to anything. typedef struct trieNode { struct trieNode *children; // The children nodes void *obj; // The object stored } TrieNode;
21
2544
by: hermes_917 | last post by:
I want to use memcpy to copy the contents of one struct to another which is a superset of the original struct (the second struct has extra members at the end). I wrote a small program to test this, and it seems to work fine, but are there any cases where doing something like this could cause any problems? Here's the small program I wrote to test this: #include <stdio.h>
6
10820
by: SB | last post by:
I feel dumb to ask because I bet this is a simple question... Looking at the code below, can someone please explain why I get two different values in my Marshal.SizeOf calls (see the commented lines)? TIA! sb
0
2330
by: Alvaro Enriquez de Luna | last post by:
Hello everybody. I am trying to use in C# a dll developed in C. I am founding problems with C structs. While my C struct does not include anything related with char or char *, everyting works ok, but when I introduce a char or char * variable in the struct, I obtain a message like this: "Method's type signature is not PInvoke compatible." Here is my code in both languages:
6
359
by: Eric | last post by:
This IS material from a CS class on object oriented programming. It is NOT my homework. Consider the following: struct A {short i; void f () {cout << "A::f()\n";}}; struct B : A {long j; void f () {cout << "B::f()\n";} void g () {cout << "B::g()\n";}}; { A* const a = new B; // dangerous (1)
74
16041
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
4
4985
by: call_me_anything | last post by:
I have different kind of data structures in different applications. The data structures are big and complex and I would like to print the members of each struct. Can we write a generic piece of code which will automatically find out the type of struct elements and print them (indented manner ?) if they are primitive types like int, float or char* ? else it will recurse into the composite data type.
0
9708
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
10588
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
10085
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
9161
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...
1
7623
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
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
5527
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...
2
3827
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2998
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.