Last Updated: February 25, 2016
·
1.216K
· bgertonson

Fun with the implicit operator

The implicit operator in C# can do some magical things for code readability. Suppose for instance, I have a class that helps enforce limits.

public class Limit
{
    private int _limit;
    public Limit(int limit)
    {
        _limit = limit;
    }

    public bool Reached(int test)
    {
        return _limit <= test;
    }
}

Now we have a Group class that limits the number of members:

public class Group
{
    private Limit _memberLimit;
    private List<Member> _members;

    public Group(Limit memberLimit)
    {
        _memberLimit = memberLimit;
    }

    public void AddMember(Member member)
    {
        if(_memberLimit.Reached(_members.Count())
            throw new LimitReachedException();
        _members.Add(member);
    }
}

To instantiate an instance of the Group class would look like this:

var group = new Group(new Limit(5));

Which is fine, but if we use the implicit operator on the Limit class we can make the code more readable. Adding the following method to the Limit class will let us avoid the inline instantiation.

public static implicit operator Limit(int limit)
{
    return new Limit(limit);
}

Now we can instantiate the Group class like this:

var group = new Group(5);

Or for more readability we can include the parameter name:

var group = new Group(memberLimit: 5);

This can add a bit of overhead when a new developer who isn't familiar with the implicit operator first starts reading the code to understand how it works. But from the standpoint of learning what the code does, this kind of readability can be very helpful.

Once you know about the implicit operator, you will start finding a lot of ways that it can be beneficial.