Friday 10 March 2017

Implicit Conversions

I've done quite a C# (re)discovery today, Implicit Conversions (aka coercion). They feel a bit confusing, but can be quite useful in some cases. This reminds me of some years ago when I found out that the cast operator could be used not just as a hint to the compiler (believe "Monsieur the Compiler" this object is not just a Book, but an SpecializedBook), but as a way to force a conversion into a different object (an explicit conversion). At that time I had already seen the existence of implicit conversions, but had not paid them attention.

Until today, if I had seen some code like this I would have not believed that it could compile:

  public static string DoFormat(string st)
  {
   return "{" + st + "}";
  }
  
  public static void Main(string[] args)
  {
   var p1 = new Person("Xuan");
   string name = p1;
   
   DoFormat(p1);
  }

Obviously a Person is not a String, so that assignment or that method call should not be allowed. The only way to do that work is by converting a Person object into a String object. But, I can not see any call to any sort of Convert method, so what?
Well, the thing is that it will work if your Person class implements an Implicit conversion to String, like this:

public class Person
 {
  public string Name {get;set;}
  public Person(string name)
  {
   this.Name = name;
  }
  
  public static implicit operator String(Person p)
  {
      return p.Name;
  }
 }

In that case the compiler will insert a call to the conversion method on its own. Just take a look into the decompiled code:

No comments:

Post a Comment