If all of the objects you would be returning are derived from a common base class, you could use a std::map<std::string,BaseClass *>. The comparisons ultimately in there somewhere, but it keeps things better organized.

Answer from jonsca on Stack Overflow
🌐
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.
🌐
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?
🌐
Techotopia
techotopia.com › index.php › Working_with_String_Objects_in_Objective-C
Working with String Objects in Objective-C - Techotopia
The string contained within a string object can be extracted and converted to an ASCII C style character string using the UTF8String method.
🌐
Apple Developer
developer.apple.com › library › archive › documentation › Cocoa › Conceptual › Strings › Articles › CreatingStrings.html
Creating and Converting String Objects
To create an NSString object from ... objects from characters in a variety of encodings. The method initWithData:encoding: allows you to convert string data stored in an NSData object into an NSString object....
🌐
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;
🌐
Florida State University
cs.fsu.edu › ~myers › cop3330 › notes › strings.html
C-strings vs. strings as objects
Do all dynamic memory management inside the class, so the user of string objects doesn't have to! Use operator overloads if more intuitive notations are desired ... Build copy constructor and assignment operator to for correct assignment and pass-by-value abilities · Build a conversion constructor to convert c-style strings to string objects, for automatic type conversions!
Find elsewhere
🌐
Bham
epweb2.ph.bham.ac.uk › user › hillier › course3cpp › howto › cstrings.html
Converting data to C++ and C-style strings
Put it towards the top of your program, then you can convert a number, for example, to a string like this: int i; string mystring; i = 15; mystring = tostring(i); FLTK (sadly) does not know about the standard C++ string class, but requires its textual information as C-style character arrays ("C strings"). For a message box or a label, you can use a literal string constant in double quotes "like this". If the text you need is not constant, but you have it in a C++ string object ...
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().

Top answer
1 of 9
33

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

2 of 9
32

Much easier way of doing it: you will need com.google.gson.Gson for converting the object to json string for streaming

to convert object to json string for streaming use below code

Gson gson = new Gson();
String jsonString = gson.toJson(MyObject);

To convert back the json string to object use below code:

Gson gson = new Gson();
MyObject = gson.fromJson(decodedString , MyObjectClass.class);

Much easier way to convert object for streaming and read on the other side. Hope this helps. - Vishesh

🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.web.ui.propertyconverter.objectfromstring
PropertyConverter.ObjectFromString(Type, MemberInfo, String) Method (System.Web.UI) | Microsoft Learn
To convert a string value to an object, use the Parse method for that object if the object provides a Parse method. For example, an Int32 object can be created from a string through the Parse method.
🌐
Reddit
reddit.com › r/csharp › convert string[] to object[]
r/csharp on Reddit: Convert string[] to object[]
November 26, 2016 -

Method below expects values to be supplied as object[], however, i have my values in string[]. The following works with hard-coded values.

var ADS_PROPERTY_DELETE = 4;

var users = new object[] {
    "CN=testUser1,OU=LabUsers,DC=Lab1,DC=contoso,DC=local",
    "CN=testUser2,OU=LabUsers,DC=Lab1,DC=contoso,DC=local"
  }

oDE.Invoke("PutEx", new object[] {ADS_PROPERTY_DELETE, "member", users});

I am unable to find a way to convert my string[] to object[].

Appreciate any assistance.

🌐
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
🌐
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:
🌐
Tutorial Teacher
tutorialsteacher.com › articles › convert-json-string-to-object-in-csharp
Parse JSON string to Class Object in C#
Now, to convert the above string to a class object, the name of the data properties in the string must match with the name of the class properties.
🌐
GeeksforGeeks
geeksforgeeks.org › objective-c › strings-in-objective-c
Strings in Objective-C - GeeksforGeeks
April 28, 2025 - In Objective-C, a string is an object that represents this sequence of characters. A string can be created using a class, which is a blueprint for creating objects. Once you have created a string object, you can use various methods to manipulate the text and perform operations on it.