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….
You can, with an implicit conversion:
Implicit conversions should only be used if no data is lost in the conversion. Even then, I recommend you use this feature sparingly, because it can make your code more difficult to read.
In this example, the implicit operator returns
nullwhen anullstring is passed. As Jon Hanna correctly commented, it is undesirable to have these two snippets of code behave differently: