Automatic type Conversion in C#

21,303

Solution 1

C# supports implicit conversion for types and you can use it for your custom types like the following:

 class CustomValue
 {
     public static implicit operator int(CustomValue v)  {  return 4;  }

     public static implicit operator float(CustomValue v) {  return 4.6f;  }
 }

 class Program
 {
     static void Main(string[] args)
     {
         int x = new CustomValue(); // implicit conversion 
         float xx = new CustomValue(); // implicit conversion 
     }
 }

And supports extension methods, but doesn't support implicit conversion as an extension method like the following:

static class MyExtension
{
    // Not supported
    public static implicit operator bool(this CustomValue v)
    {
        return false;
    }
}

Solution 2

I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

No, you are wrong. The following code won't compile:

class MyClass
{
    public override string ToString()
    {
        return "MyClass";
    }
}

static void MyMethod(string s) { }

static void Main(string[] args)
{
    MyMethod(new MyClass());   //compile error
}

The compiler will not get the type of MyMethod parameter(which is string) first and try to convert the argument you passed(whose type is MyClass) to it. I guess you are probably mislead by something like Console.WriteLine. Base on the code above, Console.WriteLine(new MyClass()) prints "MyClass" to the console, it seems that the compiler knows you should pass a string to Console.WriteLine and try to convert MyClass to string. But the essential is Console.WriteLine has several overloads, one of them is for object:

//from Console.cs
public static void WriteLine(object value)
{
    //in this method there is something like
    //Console.WriteLine(value.ToString());
}

Solution 3

I believe what you're looking for is implicit conversion, which is described here: http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx.

However, adding these to object would be a very bad idea, for reasons outlined on the page I've linked to.

Share:
21,303

Related videos on Youtube

Aivan Monceller
Author by

Aivan Monceller

Computer science is no more about computers than astronomy is about telescopes. --Edsger Dijkstra

Updated on July 09, 2022

Comments

  • Aivan Monceller
    Aivan Monceller almost 2 years

    I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

    I have written several extension methods for object type 'object'

    public static DateTime ToDate(this object date)
    {
        return DateTime.Parse(date.ToString());
    }
    
    public static int ToInteger(this object num)
    {
        return Int32.Parse(num.ToString());
    }
    
    public static long ToLong(this object num)
    {
        return Int64.Parse(num.ToString());
    }
    

    so that I could just call them like this:

    eventObject.Cost = row["cost"].ToString();
    eventObject.EventId = row["event_id"].ToLong();
    

    However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

    eventObject.Cost = row["cost"];
    eventObject.EventId = row["event_id"];
    

    The row is a DataRow if that matters.

    • Lasse V. Karlsen
      Lasse V. Karlsen over 13 years
      Why aren't you just using the Convert class? msdn.microsoft.com/en-us/library/system.convert.aspx - And no, you can't get silent type conversion like your last code there, unless you make "row[x]" return a custom object that knows how to do the implicit casting.
  • Aivan Monceller
    Aivan Monceller over 13 years
    could I add implicit operators for System.Data.DataRow?
  • Homam
    Homam over 13 years
    No, you can't because it's available only user-defined types.
  • CodesInChaos
    CodesInChaos over 13 years
    You can combine it was a ToCustomValue extension method

Related