473,804 Members | 3,462 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 6175
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.
I ran into this myself when I did:
Console.WriteLi ne("x = " + n + 1 + " elements.");
and of course it didn't work as I expected. I needed to put () around
n+1 to make it work.
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.
Ah, I haven't looked into boxing, yes, but I've seen it in top 10 list
of things to know about when learning C#.
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.)
Right.

thanks again,

Zytan

Mar 13 '07 #31
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
Ok, thanks, Bruce. Your example is clear.
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.
Yes, as do I. I prefer readability even if it's verbose.

Zytan

Mar 13 '07 #32

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
9588
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
10589
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...
1
10327
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
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
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...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3828
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.