0

Why .NET does not provide implicit or explicit conversion converting from string to the defined type and from the defined type to the string?

Example:

public class MyClass
{
  public int Id;

  public MyClass()
  {
  }
}

I can do:

var myClass = new MyClass() {Id=1};
string myClassString = myClass.ToString();

WHY I CANNOT DO?:

var myClassConverted = (MyClass) myClassString ;

Is there any serialization pattern exist can to that?

3
  • 1
    You can of course define a public static MyClass Unserialize(string s) method. Is that so unreasonable? Commented Nov 14, 2013 at 11:06
  • 1
    Thats not what ToString() is used for, take a look at BinaryFormatter, XmlSerializer or DataContractSerializer. Commented Nov 14, 2013 at 11:08
  • 1
    You don't need to use serializers. You can define your own conversion. Commented Nov 14, 2013 at 11:17

4 Answers 4

4

.ToString() is just a method , it can return any String value, this does not convert a class to a String.

We already have some questions about converting class to text:

  1. Create an instance of a class from a string
  2. C# Convert dynamic string to existing Class
  3. Convert class to string to send via email
  4. Converting Class to XML to string

Personally I use more the XML serialization approach, is very easy to serialize and deserialize and works very well with external services, like REST or SOAP.

Sign up to request clarification or add additional context in comments.

4 Comments

Well for the simple types (numerics, enums, datetime, string) it works :)
No it doesn't. Because .ToString() methods from these objects just return a String VALUE, not actually the String object.
@OndrejSvejdar: Works in what way? string i="1";int j = (int)i; will throw a compile error...
What I meant was, that for simple types the string from .ToString() is still deserializable - i.e. you can convert back the instance via Convert static class or Enum.Parse, etc.
3

ToString() is a method defined on the Object class which returns a new string instance and is not a type conversion.

There is no conversion that can be used to cast a String to your class but you can define your own custom conversion operator.

public class MyClass
{
    public int Id;

    public MyClass()
    {
    }

    public static explicit operator MyClass(string s)
    {
        MyClass temp = new MyClass() { Id = Int32.Parse(s) }; 
        // you should handle exceptions when string is not convertible to int
        return temp;
    }
}

You can then use your conversion:

MyClass c = (MyClass)("1");

From MSDN:

C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. Conversions are defined like operators and are named for the type to which they convert. Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type.

Conversion operators have the following properties:

  • Conversions declared as implicit occur automatically when it is required.

  • Conversions declared as explicit require a cast to be called.

  • All conversions must be declared as static.

You can find more on MSDN.

Comments

1

Quote from msdn Object.ToString Method :

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.

using System;

public class Example
{
   public static void Main()
   {
      Object obj = new Object();
      Console.WriteLine(obj.ToString());
   }
}
// The example displays the following output:
//      System.Object

.ToString() does not contain any unique information of your current object so you can not reconstruct the object from this string.

If you want to serialize or deserialize your object take a look here:

How to save/restore serializable object to/from file?

Comments

1

You cant really compare ToString() with a "Explicit cast". Both are different indeed.

Plausible comparison should be like this. You should be trying to cast "MyClass to string", that would fail.

Neither Cast from MyClass to string nor string to MyClass` is allowed.*[1]

var myClass = new MyClass() {Id=1};
string myClassString = (string)myClass;//Note this also will fails since no conversion beween  `MyClass` to `string`

When you compare ToString method ideally you should be comparing with FromString method unfortunately no such thing.

Back to your question

var myClassConverted = (MyClass)myClassString;

WHY I CANNOT DO?:

Because there is no implicit or explicit conversion between string to MyClass.

[1]To make it work you may use implicit or explicit operators though.

1 Comment

Thanks this i will try the explicit operator; your answer and @Szymon are what I need I think your post 1 min before him I will change and test the code now and I will mark the answer thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.