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(); 
    }
}

      

0


a source to share


4 answers


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.

+8


a source


With the implicit operator (which you have), you should simply use:



 string d = new Fred(); 

      

+1


a source


Do you want to

var b = new Fred();

will be of type fred and

var c = new Fred();

for a string like? Although the declarations are identical?

As mentioned by other posters, when you declare a new Fred () it will be of type Fred unless you specify what it should be string

+1


a source


Unfortunately, in the example c is of type Fred. While Freds can be thrown into the lines, c is ultimately Fred. To force d to a string, you have to tell it to pass Fred as a string.

If you really want c to be a string, why not just declare it as a string?

0


a source







All Articles