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?

Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70

4 Answers4

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.

Community
  • 1
  • 1
Wagner Leonardi
  • 4,226
  • 2
  • 35
  • 41
  • Well for the simple types (numerics, enums, datetime, string) it works :) – Ondrej Svejdar Nov 14 '13 at 11:12
  • No it doesn't. Because .ToString() methods from these objects just return a String VALUE, not actually the String object. – Wagner Leonardi Nov 14 '13 at 11:24
  • @OndrejSvejdar: Works in what way? `string i="1";int j = (int)i;` will throw a compile error... – Chris Nov 14 '13 at 11:31
  • 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. – Ondrej Svejdar Nov 14 '13 at 12:12
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.

Community
  • 1
  • 1
Szymon
  • 42,577
  • 16
  • 96
  • 114
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?

Community
  • 1
  • 1
user1567896
  • 2,398
  • 2
  • 26
  • 43
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.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 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. – Bassam Alugili Nov 14 '13 at 11:47