Implicit Operators in C# are really cool, they allow you to convert an object to another without specifying an explicit cast.
//Lets pretend this is some usefull program
using System;
public class Program
{
public static void Main ()
{
//wait this cannot possibly compile.... can it?
FridgeItem myFridgeItem = "Hello World";
//yes it does, implicit fool!!
Console.WriteLine(String.Format("my name is {0},
my expiration date is {1},
and my purchase date is {2}",
myFridgeItem.Name, myFridgeItem.Expires,
myFridgeItem.PurchaseDate));
}
}
//some useless object
public class FridgeItem
{
public string Name { get; set; }
public DateTime Expires { get; set; }
public DateTime PurchaseDate { get; set; }
//this is where the fairy dust goes
public static implicit operator FridgeItem (string stuff)
{
//we convert a string into something else.
var item = new FridgeItem
{
Name = stuff.ToUpper(),
//we just add random stuff here.
PurchaseDate = DateTime.Now,
Expires = DateTime.Now.AddDays(30),
};
return item;
}
}
use responsibly.