Bassam Alugili
Bassam Alugili

Reputation: 16993

Convert the user defined type to string and string to user defined type

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?

Upvotes: 0

Views: 4773

Answers (4)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

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.

Upvotes: 1

Szymon
Szymon

Reputation: 43023

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.

Upvotes: 3

Wagner Leonardi
Wagner Leonardi

Reputation: 4446

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

Upvotes: 4

user1567896
user1567896

Reputation: 2398

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?

Upvotes: 1

Related Questions