views:

130

answers:

4

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(); 
    }
}
+8  A: 

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.

Mehrdad Afshari
Yes, got that much. Was hoping that without a cast or typing, I could get Fred() to return a string. Maybe reading too much into this.
Andrew Robinson
Indeed, the casting is done implicitly... You could pass `new Fred()` to a method expecting an string without any cast. But the compiler can't really do magic and infer your intention without any clues.
Mehrdad Afshari
To all, I think that I am seeing the comedy of my quesiton. Thanks
Andrew Robinson
Don't worry about it, it's one of those things that seems like a really tough question until you ask someone else, and then they look at you like you're nuts.
+1  A: 

With an implicit operator (which you have) you should just be able to use:

 string d = new Fred();
Marc Gravell
Yes, got that much. Was hoping that without a cast or typing, I could get Fred() to return a string.
Andrew Robinson
+1  A: 

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

A: 

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?

Aric TenEyck