Automatic type Conversion in C#
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;
}
}
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());
}
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.