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 31 6172
>1. why does it complain without "override"? and
Because a method with the same signature is defined in a base class
(System.Object in this case).
>2. why isn't it automatically invoked?
In what situation is it not invoked? The following prints "Hello
Hello" as expected for me
public struct MyStruct
{
public override string ToString()
{
return ("Hello");
}
}
class Test
{
static void Main()
{
MyStruct m = new MyStruct();
Console.WriteLi ne("Hello " + m);
}
}
Mattias
--
Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Zytan <zy**********@y ahoo.comwrote:
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.
In what situation? Here's a test which shows it being invoked:
using System;
public struct MyStruct
{
public override string ToString()
{
return ("Hello");
}
}
class Test
{
static void Main()
{
MyStruct foo = new MyStruct();
Console.WriteLi ne (foo);
}
}
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).
It still (sort of) derives from object - you are genuinely overriding a
method here. The details are pretty fiddly.
So:
1. why does it complain without "override"? and
Because then you'd be hiding the method instead of overriding it.
2. why isn't it automatically invoked?
When are you expecting it to be 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.
Without more details of when you'd expect it to be invoked, it's
impossible to answer you.
Could you post a short but complete program which demonstrates the
problem?
See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
--
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
I don't know what you are doing wrong. It should work.
---------------------------------
using System;
class Test
{
public static void Main()
{
MyStruct x = new MyStruct();
Console.WriteLi ne("{0}", x);
}
}
public struct MyStruct
{
public override string ToString()
{
return ("Hello");
}
}
-----------------------------------
This definitely prints "Hello"
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** *************@j 27g2000cwj.goog legroups.com...
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
Ok, you guys rock, thanks for posting the code samples. Jon, I've
created a 'complete' program that shows the error (and yes, it
certainly helps to narrow down exactly what is wrong, and most often
shows the err in your ways). The problem occurs when I have my *own
function* that accepts a string. In this case, the conversion from
struct to string does not implicitly take place.
class Program
{
public struct MyStruct
{
public int x;
public override string ToString()
{
return "Hello!";
}
}
static void Main(string[] args)
{
MyStruct s;
s.x = 5;
Print(s); // doesn't compile
Print(s.ToStrin g()); // compiles
}
static void Print(string s)
{
Console.WriteLi ne(s);
}
}
Zytan
1. why does it complain without "override"? and
>
Because a method with the same signature is defined in a base class
(System.Object in this case).
Ok, so, structs DO derive from object. Strange. I guess the evidence
suggest that, doesn't it?
2. why isn't it automatically invoked?
In what situation is it not invoked?
Please see my program in another post in this thread.
Thanks, Mattias
Zytan
But, it doesn't get automatically invoked.
>
In what situation?
Please see my program in another post.
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).
It still (sort of) derives from object - you are genuinely overriding a
method here. The details are pretty fiddly.
Ah.
So:
1. why does it complain without "override"? and
Because then you'd be hiding the method instead of overriding it.
Yes, of course. Now that I know it's derived from object, it makes
sense.
2. why isn't it automatically invoked?
When are you expecting it to be automatically invoked?
It's when I pass it to my own function that accepts a string
parameter.
Please see the program in another post.
Thanks, Jon
Zytan
I don't know what you are doing wrong. It should work.
I don't think I am doing anything wrong. Call your own function that
takes a string instead of Console.WriteLi ne in your program, and
you'll see that it doesn't work.
Please see my program in another post.
Thanks, Bill.
Zytan
Zytan <zy**********@y ahoo.comwrote:
Ok, you guys rock, thanks for posting the code samples. Jon, I've
created a 'complete' program that shows the error (and yes, it
certainly helps to narrow down exactly what is wrong, and most often
shows the err in your ways). The problem occurs when I have my *own
function* that accepts a string. In this case, the conversion from
struct to string does not implicitly take place.
No, it doesn't - and it doesn't for classes either, thankfully. Why did
you expect that it would?
You could add your own implicit conversion to a string, although I
wouldn't recommend it.
--
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
"Zytan" <zy**********@y ahoo.comwrote in message
news:11******** **************@ 64g2000cwx.goog legroups.com...
>I don't know what you are doing wrong. It should work.
I don't think I am doing anything wrong. Call your own function that
takes a string instead of Console.WriteLi ne in your program, and
you'll see that it doesn't work.
You could overload your Print method a few times to get the behavior
that you desire
for instance, this would work.
static void Print(object obj)
{
Console.WriteLi ne(obj);
}
You could make your Print method accept formatting strings as well if
you write those overloads
Good luck
Bill This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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;
|
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>
|
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
|
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:
| |
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)
|
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
|
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.
|
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...
|
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...
|
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,...
| |
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |