Menu

How to Like C#

November 23, 2013 - .NET, C#, Visual Basic

Visual Basic has a useful Operator, the “Like” Operator. Observe it in action:

The Like operator is a pattern matching operator. It can be useful in many situations and is certainly a lot shorter to use than fiddling about with Regular Expression Objects, matches, etc. So the question becomes, how can we best bring this to C#? We could have a static method in a separate class:

And use it like this:

But that’s not very concise. One alternative is to cheat and use operator overloads; we can’t define a new operator full stop, but we can fake it by creating a new class and a explicit operator for it that converts a string. Resulting in something like this:

In order to do this, we need as mentioned a new class that has an explicit cast from a String as well as an equality operator.

And… That’s it! Now you can have something approximating the Like Operator. Note that because it uses Regular Expressions it’s not actually the Like Operator, which is more restricted. If you really need exact replication of VB.NET’s Like Operator, you can create an Assembly in VB.NET and expose a public function that simply returns the result of a Like Operator on it’s parameters.

Have something to say about this post? Comment!