I know that I can use implicit conversions with a class as follows but is there any way that I can get a instance to return a string without a cast or conversion?
public class Fred
{
public static implicit operator string(Fred fred)
{
return DateTime.Now.ToLongTimeString();
}
}
public class Program
{
static void Main(string[] args)
{
string a = new Fred();
Console.WriteLine(a);
// b is of type Fred.
var b = new Fred();
// still works and now uses the conversion
Console.WriteLine(b);
// c is of type string.
// this is what I want but not what happens
var c = new Fred();
// don't want to have to cast it
var d = (string)new Fred();
}
}
In fact, the compiler will implicitly cast Fred
to string
but since you are declaring the variable with var
keyword the compiler would have no idea of your actual intention. You could declare your variable as string and have the value implicitly casted to string.
string d = new Fred();
Put it differently, you might have declared a dozen implicit operators for different types. How you'd expect the compiler to be able to choose between one of them? The compiler will choose the actual type by default so it won't have to perform a cast at all.