0

Is it possible to implement method to call like

if (myString is Email)

where Email is a class name and actual validation is performed under "is", not just type checking.

Not for real world projects, just curious.

Pavel Oganesyan
  • 6,774
  • 4
  • 46
  • 84
  • 3
    No. You can't override the `is` operator. https://msdn.microsoft.com/en-us/library/8edha89s.aspx?f=255&MSPPError=-2147217396 – Jeroen Vannevel Aug 03 '15 at 14:04
  • If Email is a class, cant you change the question to if (Email.IsValid(mystring)) and have as much logical readability? – BugFinder Aug 03 '15 at 14:07
  • 1
    @JeroenVannevel: Its overloading and not overriding – Nikhil Agrawal Aug 03 '15 at 14:08
  • @BugFinder Yes, totally. I was not looking for an actual solutions, just thinking about possible syntax sugar. Thank you for attention. – Pavel Oganesyan Aug 03 '15 at 14:08
  • 1
    @NikhilAgrawal: I always thought the official docs didn't make much sense for calling it overloadable operators but you just made me realize why it's overloading and not overriding. Cheers ;) – Jeroen Vannevel Aug 03 '15 at 14:10
  • Predicting future interesting questions, [click](http://stackoverflow.com/q/1040114/1997232). – Sinatr Aug 03 '15 at 14:10

2 Answers2

3

No you can't because is operator cannot be overloaded. Read here

Why don't you create a custom extension method and check in that method.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

You may find useful a partial solution via operator:

  public class Email {
    ...
    public static implicit operator Email(String value) {
      if (...) // validate value here
        return null; // <- not an actual Email

      // Email
      return new Email(value);
    }
  }

  ....

  Email email = "SomeAddress@SomeServer.com";

  if (email != null) {
    ...
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215