Reputation: 22578
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();
}
}
Upvotes: 0
Views: 239
Reputation: 8032
Unfortunately, in the example, c is of type Fred. While Freds can be cast to strings, ultimately, c is a Fred. To force d to a string, you have to tell it to cast the Fred as a string.
If you really want c to be a string, why not just declare it as a string?
Upvotes: 0
Reputation: 8336
you want
var b = new Fred();
to be of type fred, and
var c = new Fred();
to be of type string? Even though the declarations are identical?
As mentioned by the other posters, when you declare a new Fred(), it will be of type Fred unless you give some indication that it should be a string
Upvotes: 1
Reputation: 1064184
With an implicit operator (which you have) you should just be able to use:
string d = new Fred();
Upvotes: 1
Reputation: 422270
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.
Upvotes: 8