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 - In C# object is the root class ... it may be derived or parent classes the object is to be created by using Object.toString() method it returns the string as the result....
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
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.

🌐
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:
🌐
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;
🌐
Post.Byes
post.bytes.com › home › forum › topic › c sharp
Fastest way to convert an object to a string - Post.Byes
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.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › fundamentals › runtime-libraries › system-object-tostring
System.Object.ToString method - .NET | 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 ...
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.object.tostring
Object.ToString Method (System) | Microsoft Learn
The returned string should be as short as possible so that it is suitable for display by a debugger. Your ToString() override should not return Empty or a null string. Your ToString() override should not throw an exception.
Top answer
1 of 9
59

The two are intended for different purposes. The ToString method of any object is supposed to return a string representation of that object. Casting is quite different, and the 'as' key word performs a conditional cast, as has been said. The 'as' key word basically says "get me a reference of this type to that object if that object is this type" while ToString says "get me a string representation of that object". The result may be the same in some cases but the two should never be considered interchangeable because, as I said, they exist for different purposes. If your intention is to cast then you should always use a cast, NOT ToString.

from http://www.codeguru.com/forum/showthread.php?t=443873

see also http://bytes.com/groups/net-c/225365-tostring-string-cast

2 of 9
33

If you know it is a String then by all means cast it to a String. Casting your object is going to be faster than calling a virtual method.

Edit: Here are the results of some benchmarking:

============ Casting vs. virtual method ============
cast 29.884 1.00
tos  33.734 1.13

I used Jon Skeet's BenchmarkHelper like this:

using System;
using BenchmarkHelper;

class Program
{
    static void Main()
    {
        Object input = "Foo";
        String output = "Foo";

        var results 
           = TestSuite.Create("Casting vs. virtual method", input, output)
            .Add(cast)
            .Add(tos)
            .RunTests()
            .ScaleByBest(ScalingMode.VaryDuration);

        results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
                results.FindBest());
    }

    static String cast(Object o)
    {
        return (String)o;
    }

    static String tos(Object o)
    {
        return o.ToString();
    }
}

So it appears that casting is in fact slightly faster than calling ToString().

🌐
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 ...
🌐
Florida State University
cs.fsu.edu › ~myers › c++ › notes › stringobj.html
String Objects: The string class library
While there are some library functions that work with C-strings, programmer still has to be careful to make correct calls. These library functions do not protect boundaries either! Less intuitive notation for such usage (library features) Recall that C++ allows the creation of objects, specified ...
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}'.

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.

🌐
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:...
🌐
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

🌐
Fluent C++
fluentcpp.com › home › using tostring on custom types in c++
Using toString on Custom Types in C++ - Fluent C++
August 4, 2020 - it would “keep simple things simple”, by leaving the powerful tools like streams to more complex tasks (involving several objects or formatting), well, nearly every other language does it. It’s not that we need to copy others languages, but in my opinion not having a tool for this simple task doesn’t help with the image of C++ being a complex language. Now, there is existing code, implementing custom to_string methods, stream operations, and there is also the standard std::to_string for numerical types.
🌐
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).
🌐
UiPath Community
forum.uipath.com › help › studio
How can i Convert a String into a Object[] in C# - Studio - UiPath Community Forum
January 18, 2023 - Hello! I need to Convert a String into a Array of Object in C# Can anybode help me?
🌐
Reddit
reddit.com › r/learnpython › converting class object to string
r/learnpython on Reddit: Converting class object to string
October 4, 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!