Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string constants in implicit conversion

Consider the following code:

public class TextType {

    public TextType(String text) {
        underlyingString = text;
    }

    public static implicit operator String(TextType text) {
        return text.underlyingString;
    }

    private String underlyingString;
}

TextType text = new TextType("Something");
String str = text; // This is OK.

But I want to be able do the following, if possible.

TextType textFromStringConstant = "SomeOtherText";

I can't extend the String class with the TextType implicit operator overload, but is there any way to assign a literal string to another class (which is handled by a method or something)?

String is a reference type so when they developed C# they obviously had to use some way to get a string literal to the class. I just hope it's not hardcoded into the language.

like image 542
Kornelije Petak Avatar asked Jan 24 '10 18:01

Kornelije Petak


2 Answers

public static implicit operator TextType(String text) {
    return new TextType(text);
}
like image 192
ChaosPandion Avatar answered Oct 17 '22 23:10

ChaosPandion


Add

public static implicit operator TextType(string content) {
  return new TextType(content);
}

to your class? :)

like image 27
Benjamin Podszun Avatar answered Oct 17 '22 23:10

Benjamin Podszun