Initiative: Red Dawn



June 8, 2016

Save code by using the implicit keyword

Most likely you’ll have your own custom classes for your game. Classes such as Unit, City, Planet, etc. In many places, you will need to access them to perform game operations. When you do that, it is a good practice to check if the class is null and handle such error, to avoid an unwanted exception. You can use exceptions and try/catch if you want, but if you, for any reason, don’t want to use it, then you can easily check if its null. like so:
        if (unit != null) {             // Handle unit here         }
If instead, you do this:
        if (unit) {             // Handle unit here         }
You will get a compiler error similar to this one:
error CS0029: Cannot implicitly convert type `Unit’ to `bool’
But if you add an implicit keyword to your class:
public class Unit {     public static implicit operator bool (Unit unit) {         return (unit!=null);     }     // The rest of the class here... }
Then you will be able to use “if (unit)” without issues. Now granted, doing “if (unit != null)” is not a huge deal, really. So, what’s the big fuzz about using the implicit keyword? Well, there are lots of cool implementations you can do to make things in your game easier. Above we created an implicit conversion to “bool”, but we can create implicit conversions to anything. WARNING: The implicit keyword on classes should be used with extreme caution. Think seriously if you need it and why you need it. Using the implicit keyword between Classes is usually a representation of incorrect object design, as those classes should inherit between themselves. Here’s another example: let’s say your Unit class has a unitId, to access it you can use a property or a function. But you may want your Unit class to convert itself implicitly to its id when you need an int. Here’s how that would be accomplished. This is the Unit class:
public class Unit {     public static implicit operator bool (Unit unit) {         return (unit!=null);     }     public static implicit operator int (Unit unit) {         return (unit.m_unitId);     }     public int m_unitId = 1;     // The rest of the class here... }
And now, you can simply do:
        Unit unit = new Unit();         int unitId = unit;
And you will get the unit id. Without it, you would simply get an error like this:
Cannot implicitly convert type `Unit’ to `int’
Now you can actually see the power of using the implicit keyword. It can greatly simplify your game code if used correctly. Again, you must use it with care, though, as implementations like this can easily fall through the cracks. If your conversions are deeper or need more process, it’s better to use explicit conversions. Don’t forget to follow us on twitter for news regarding articles and game development [twitter-follow screen_name=’indelvestudios’]    

Leave a Reply