Create custom string class

Viewed 17913

I want to create my own EMailAddress class that acts like a string class.

So I like to do this

private EMailAddress _emailAddress = "Test@Test.com";

instead of

private EMailAddress _emailAddress = new EMailAddress("Test@Test.com");

Is there any way to accomplish what I want, or do I need to use the second alternative. Since string is sealed I can't use that, and the = operator can't be overloaded so I am out of ideas how to fix this....

6 Answers

As a follow-up to @Thorarin's code:

You could use this as base code and add extra features that a normal string class would have:

public class VarChar
{
        private string _content;

        public VarChar(string argContent)
        {
            _content = argContent;
        }

        public static implicit operator VarChar(string argContent)
        {
            if (argContent == null)
                return null;

            return new VarChar(argContent);
        }

        public static implicit operator string(VarChar x) => x._content;

        public override string ToString()
        {
            return _content;
        }
}

So the following code just works:

VarChar tempVarChar = "test";

string tempTest = tempVarChar; // = "test"

var tempText = tempVarChar.ToString();

tempVarChar = tempVarChar + "_oke";

tempText = tempVarChar; // = "test_oke"
Related