No need to reinvent the wheel. Use Json.Net

string s = JsonConvert.SerializeObject(yourObject);

That is all.

You can also use JavaScriptSerializer

string s = new JavaScriptSerializer().Serialize(yourObject);
Answer from I4V on Stack Overflow
🌐
EDUCBA
educba.com › home › software development › software development tutorials › c# tutorial › c# object to string
C# Object to String | How Object to String function work in C#
April 3, 2023 - We create the object and covert it by using ToString() method. ... using System; public class demo { private int integers; private string stringsfirst; private int secondinteger; private string secondstrings; private string thirdstrings; public ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Discussions

c++ - Convert Class Object to String - Stack Overflow
I have an assignment for a class that requires me to convert a class object, clock_time, to a string using two required, instructor-defined empty functions: to_string() and an overloaded More on stackoverflow.com
🌐 stackoverflow.com
Convert char object to string
Hi ı am trying to learn arduino. How ı can convert string object to char object. This is not working String object="hello"; char (object)=object; More on forum.arduino.cc
🌐 forum.arduino.cc
15
0
June 5, 2021
Converting class object to string
I tried writing a magic str() method which did convert them to "O", but then, instead of a 2d grid, it turned into a vertical line of O's. You're adding the \n linefeed character to the end of every string. Why are you doing that? Why are you iterating at all? Nothing about your approach makes any sense. If the elements of the grid are objects, and you want each object visualised either as a O or ., then it's pretty straightforward to make each element responsible for its own visualization: class ThingThatCanBeBigOrSmall: def __str__(self): if self.is_big: # or whatever the state variable is return "O" else: return "." More on reddit.com
🌐 r/learnpython
1
1
November 10, 2020
How to convert an object to a string? - C++ Forum
So let's say that we have a class called Date for example. And you want to convert an object of a date to a string, so you can do this: More on cplusplus.com
🌐 cplusplus.com
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.object.tostring
Object.ToString Method (System) | Microsoft Learn
Types commonly override the Object.ToString method to return a string that represents the object instance. For example, the base types such as Char, Int32, and String provide ToString implementations that return the string form of the value ...
🌐
CodeProject
codeproject.com › Questions › 128583 › How-to-convert-object-into-string
https://www.codeproject.com/Questions/128583/How-t...
Copyright © 1999-2026 GoDaddy, LLC. All rights reserved.Privacy Policy · Disclaimer: References to any specific company, product or services on this Site are not controlled by GoDaddy.com LLC and do not constitute or imply its association with or endorsement of third party advertisers.
Top answer
1 of 1
14

The crux of the problem is the to_string method uses the operator<< overload for clock_time. Unfortunately, The operator<< overload uses the to_string method. Obviously this can't work because it's going to go around in circles forever.

So how do we fix it up so that it can work?

We uncouple to_string and operator<< so that they don't call each other.

First off, let's define a bogus example clock_time because it's missing and we can't do jack all without it.

class clock_time
{
    int hour;
    int minute;
    int second;

public:
    friend std::ostream& operator<<(std::ostream &out, clock_time c);
}

Note the declaration of operator<< as a friend function of clock_times. This allows operator<< to break encapsulation and use the private members of clock_time. This might not be necessary depending on how clock_time has been defined, but for this example, it's pretty much the key to the whole shebang.

Next we implement operator<<

ostream& operator<<(ostream &out, clock_time c)
{
    out << c.hour << ":" << c.minute << ":" << c.second;
    return out;
}

I've chosen this output format because it's what I expect to see on a digital clock. The Law of Least Surprise says give people what they expect and you'll have fewer bugs and bad feelings. Confuse people and... Well remember what happened with when Microsoft pulled the start menu from Windows 8? Or when Coke changed their formula?

I'm doing operator<< first because of personal preference. I'd rather do the grunt work here because it's easier on my brain than doing it in to_string for some reason.

Now we're ready to implement the to_string function.

string to_string(clock_time c)
{
    ostringstream ss;
    ss << c;
    return ss.str();
}

Surprise! It's exactly the same as OP originally implemented it. Because to_string and operator<< have been uncoupled, operator<< is available for use in to_string. You could do it the other way around, so long as one of the functions does the heavy lifting for the other. Both could also do all of the work, but why? Twice as many places to screw things up.

🌐
Arduino Forum
forum.arduino.cc › projects › programming
Convert char object to string - Programming - Arduino Forum
June 5, 2021 - Hi ı am trying to learn arduino. How ı can convert string object to char object. This is not working String object="hello"; char (object)=object;
Find elsewhere
🌐
Florida State University
cs.fsu.edu › ~myers › cop3330 › notes › strings.html
Strings: C-strings vs. strings as objects
Build a conversion constructor to convert c-style strings to string objects, for automatic type conversions!
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › fundamentals › runtime-libraries › system-object-tostring
System.Object.ToString method - .NET | Microsoft Learn
January 29, 2024 - Types commonly override the Object.ToString method to return a string that represents the object instance. For example, the base types such as Char, Int32, and String provide ToString implementations that return the string form of the value ...
🌐
Reddit
reddit.com › r/learnpython › converting class object to string
r/learnpython on Reddit: Converting class object to string
November 10, 2020 -

Hi all. I am trying to code a small scale "game" for an assignment and have gotten a bit stuck. I have created a nested list like a 2d grid with a class, whose elements consist of class objects from another class. this turned out to be rather difficult to decipher as it only returns class.Class object at <address>. I want the program to represent the objects with either the string "O" or ".". I do, however, not have a single clue as to how to do this. I tried writing a magic str() method which did convert them to "O", but then, instead of a 2d grid, it turned into a vertical line of O's. here's the code for that attempt :

def __str__(self) :
    tekst = " "
    for self._radliste in self._brett :
        tekst+= ""
        for kololiste in self._radliste :
            if str(kololiste) == "." :
                tegn = "."
            else :
                tegn = "O"
            tekst += tegn + "\n"
        #tekst += "\n" + "\n"
    return tekst

later I tried

def __str__(self):
    for a in self._brett :
        for b in a :
            for c in b :
                Celle.hentStatusTegn(c)
                if c == "." :
                    tegn =  "."
                elif  c == "O" :
                    tegn = "O"
    return tegn

which did nothing.

The code for the class I am using will be put down below. these snippets all work.

import random from celle import Celle

class Spillebrett :

def __init__(self, rader, kolonner) :

    self._rader = rader

    self._kolonner = kolonner

    self._brett = []

    self._radliste = []

    for i in range(self._kolonner) :

        kololiste = []

        for y in range(self._rader) :

            objektet = Celle()

            kololiste.append(objektet)

        self._radliste.append(kololiste)

    for x in self._radliste :

        print(x)

    gen = 0

    self._genererer()

    self.tegnBrett(rader)

and then the code for creating the board (or so I thought).

def tegnBrett(self, rader) :
    self._brett = []
    for i in self._radliste :
        self._brett.append([])
        for j in i :
            self._brett.append(self._radliste)
    #for i in range(15) :
        #print(" ")
    return self._brett

I am not getting any errors.

sorry for the long post, it's my first time posting here and I hope any experienced programmers can help me out! thank you!

🌐
Cplusplus
cplusplus.com › forum › general › 268772
How to convert an object to a string? - C++ Forum
So let's say that we have a class called Date for example. And you want to convert an object of a date to a string, so you can do this:
🌐
Post.Byes
post.bytes.com › home › forum › topic › c sharp
Fastest way to convert an object to a string - Post.Byes - Bytes
November 29, 2006 - Re: Fastest way to convert an object to a string Thanks for the reply, First may I say that the object is converted to a byte array via BinaryStream using serialization. I use the MemoryStream to store the data. I'm already aware how StringBuilders works and know that using the String object to manupulate the string is expensive.
🌐
Cplusplus
cplusplus.com › reference › string › string
std::string
The string class is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type, with its default char_traits and allocator types (see basic_string for more info on the template). Note that this class handles bytes independently of the encoding used: If used to handle sequences of multi-byte or variable-length characters (such as UTF-8), all members of this class (such as length or size), as well as its iterators, will still operate in terms of bytes (not actual encoded characters).
🌐
Florida State University
cs.fsu.edu › ~myers › c++ › notes › stringobj.html
String Objects: The string class library
The string library also includes versions of the insertion and extraction operators, for use with string objects · The insertion operator is used as with any other variable, and it will print the contents of the string: string s1 = "Hello, world"; string s2 = "Goodbye, cruel"; cout << s1; // prints "Hello, world" cout << s2 + " world"; // prints "Goodbye, cruel world" The extraction operator, like the one for c-strings, will skip leading white space, then read up to the next white space (i.e.
Top answer
1 of 8
5

s(message) actually calls the constructor of std::string, which constructs a new object of this type from the given character array pointed to by message. s is just an arbitary name given to the string object. std::string is C++'s idiomatic object for working with strings, it is usually preferred over raw C strings.

Consider this simple sample:

// Declare a fresh class
class A {

   public:

      // a (default) constructor that takes no parameters and sets storedValue to 0.
      A() {storedValue=0;}

      // and a constructor taking an integer
      A(int someValue) {storedValue=someValue;}

   // and a public integer member
   public:
      int storedValue;
};

// now create instances of this class:
A a(5);

// or
A a = A(5);

// or even
A a = 5;

// in all cases, the constructor A::A(int) is called.
// in all three cases, a.storedValue would be 5

// now, the default constructor (with no arguments) is called, thus
// a.storedValue is 0.
A a;

// same here
A a = A();

std::string declares various constructors, including one that accepts a const char* for initialization - the compiler automatically chooses the right constructor depending on the type and number of the arguments, so in your case string::string(const char*) is choosen.

2 of 8
1

That is actually one of the constructors of std::string.

In C++, you can create objects a few different ways.

std::string s = "Hello"; // implicit constructor using const char *
std::string s = std::string("Hello"); // invoke the const char* constructor of std::string
std::string s("Hello"); // another way to do the stuff above

There are more ways than that, but just to demonstrate how you could create this std::string object.

🌐
Reddit
reddit.com › r/javahelp › how to convert object to string ?
r/javahelp on Reddit: How to convert object to string ?
October 7, 2020 -

Hello guys, I would like to know the best way to convert object to string with commas separating the year month & day in format (yyyy,mm,dd) . I am trying to do so for the program to place information into a data file. The conversion follows the code line below. I seek your kind assistance and many thanks.

MyDate MyDate = cannedFood.getexpiryDate(); // to convert object MyDate into string

🌐
Quora
quora.com › How-do-I-convert-a-string-array-to-an-object-in-C
How to convert a string array to an object in C - Quora
Answer (1 of 3): A string array already is an object in C. In C parlance, an object is a region of memory which is used by the program to store a particular piece of information. C does not use the object oriented paradigm, so the modern programming connotations don’t really apply.
🌐
Bham
epweb2.ph.bham.ac.uk › user › hillier › course3cpp › howto › cstrings.html
Converting data to C++ and C-style strings
int i; string mystring; i = 15; ... this". If the text you need is not constant, but you have it in a C++ string object (perhaps by using the tostring function above) you can just use its c_str() function, e.g:...
Top answer
1 of 6
9

Rust's approach: Display and Debug traits

Rust uses the trait system, through the Display and Debug traits, to model types that may be converted to strings, with two possible and well-known uses (user-facing and developer-facing, respectively).

However, it statically ensures that values of a type that doesn't implement the Display trait may not be used to construct a string representation; the same for Debug. Hence, Rust doesn't have a default string representation for user-defined types.

Even though there is not a default string representation, the language offers a macro to derive the Debug implementation using a sensible default that follows the type's definition. However, the Display trait may not be derived, which forces the developer to implement the user-facing string conversion explicitly.


Haskell has a similar mechanism via the Show type class, which may be derived.

2 of 6
5

Another option is to simply forbid string coercion, as e.g. Python does. This makes it the programmer's responsibility to explicitly convert other values to strings where necessary, but also means there is no uniquely privileged way to convert to a string.

In Python for example, there are the str and repr functions which convert values to strings in different ways (and which can have user-defined behaviour via the __str__ and __repr__ dunder methods), but you can also convert to string through other means, such as by calling some other method defined by the object's class, or using string formatting or f-strings which may offer more options for how the conversion is done, such as f'{x:.02f}'.