8

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.

1
  • See section 10.10.3 of the specification for details. Commented Jan 24, 2010 at 20:13

2 Answers 2

9
public static implicit operator TextType(String text) {
    return new TextType(text);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Fix text != value - you were faster though :)
I can't believe how I missed that operator overloads goes both ways. I had a feeling the method would have to belong to the String class... Thanks.
6

Add

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

to your class? :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.