#396 – Operators as Class Members

In C#, an operator is a symbol that defines some operation that should take place when evaluating an expression.

For example, the plus sign (+) is an operator that is typically used to add two numbers, or two instances of a class.

            int a = 5 + 6;   // 11
            string s = "Corn" + "dog";   // Corndog

For most operators, if you try using them on instances of a class that you define, the operator will have no meaning and you’ll get a compile-time error.  (With the exception of the equality (==) and inequality (!=) operators, which are automatically defined for every type).

If you want a particular operator to make sense for instances of a class that you define, you can define that operator as a member of your class.  For example, I could define the plus (+) operator for the Dog class, such that it merges the dog’s names and adds their ages.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: