Implicit conversion class
I know that I can use implicit conversions with a class like this, but is there a way that I can get an instance to return a string without conversion 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();
}
}
a source to share
In fact, the compiler would implicitly cast Fred
in string
, but since you are declaring a variable with a keyword var
, the compiler would have no idea of your actual intent. You can declare your variable as a string and have a value, implicit expression in the string.
string d = new Fred();
Put it this way, you could declare a dozen implicit operators for different types. How do you expect the compiler to be able to pick one of these? The compiler will choose the actual default type, so it won't have to do casting at all.
a source to share