I was recently trying to create my own "CaseInsensitiveString" class to behave as if character case did not matter in terms of comparison; this is easy enough, or at least it sounds like it is.
The first thing I did was override the Equals method to allow for case-insensitive comparison; easy enough. Next I added operator == and operator != for easier comparison syntax; easy enough. I also wanted to make my class be assignable from a string, and have it be implicitly castable to a string; easy enough, just provide an implicit operator string(MyClass) and an implicit operator MyClass(string). After righting some quick sanity unit-tests, a problem arose: all of these assertions work in this unit test:
However, line 7 will not work. Why?
After a little research, I found out that nUnit's Assert.IsTrue method is invoking the following version of System.String.Equals:
Microsoft's implementation of this code is as follows:
Do you see the problem yet? The "as" keyword, for whatever reason, does not invoke any casting operators! I find it strange that an explicit cast would work in this instance, or even an implicit cast, but not the "as" keyword.
The moral of the story is if you are using implicit type conversion operators, use the "as" keyword only if you only want the object in question to be explicitly casted to the type you provide. The “as” keyword works fine with inheritance chains (as well as the “is” keyword). However, in implicit type conversion operators it will not allow other objects to cast to the target.