How to work around not being able to overload the ‘=’ operator!

Hey guys, I know for some of you this is probably no big deal and you do this all the time, but it was something that took me a while to figure out and I wanted to share it with everyone!

Today I was working on a program in Unity that helps make schedules for the place that I work for(pm me for details on that if you're interested at all), and I needed a way to store data about day to day availability. Initially I was using bools to state if they could work that day, then using ints for each days start and end, but that got to be messy and there was just too many vars floating around for one small script.

So I wanted to make a type for day that holds onto the bool and the start and end time. Well that is no big deal we make types all the time, but the catch to this is that I made heavy use of the bool types, and wanted to make it so that I could continue to use them like that. Example:

 if (sun) { } else if (mon) { } else if (tue) { } else if (wed) { } else if (thu) { } else if (fri) { } else if (sat) { } 

So I wanted to find a way to let me use these new Day types as bools. That part was easy, just overload the true and false operators.

public static bool operator true(Day d) { return d.available; } public static bool operator false(Day d) { return d.available; } 

The part where the challenge came into effect is in the constructors. I wanted to still be able to pass bool values to the day type like you would a regular bool.

 public Employee(string _name, int _id, bool _fulltime, bool _sun, bool _mon, bool _tue, bool _wed, bool _thu, bool _fri, bool _sat) { empName = _name; empID = _id; fulltime = _fulltime; sun = _sun; mon = _mon; tue = _tue; wed = _wed; thu = _thu; fri = _fri; sat = _sat; } 

Which is where I ran into the problem that I needed to solve. Since the day type on the left isnt a bool I needed to overload the = operator. Since that cant be done in C#(for good reason[Link]), I had to figure out a way to cheat it!

The way I was able to solve this was by overloading the + operator.

 public static Day operator +(Day d, bool t) { return new Day(t, d.startTime, d.endTime); } 

By overloading the + operator, it allowed me to use += to assign bools to the Day type like you would have to a normal bool without interfering with the other data the type held.

End result:

 public Employee(string _name, int _id, bool _fulltime, bool _sun, bool _mon, bool _tue, bool _wed, bool _thu, bool _fri, bool _sat) { empName = _name; empID = _id; fulltime = _fulltime; sun += _sun; mon += _mon; tue += _tue; wed += _wed; thu += _thu; fri += _fri; sat += _sat; } 

by TheCatalyse via /r/csharp

Leave a Reply