Defining implicit and explicit casts for C# interfaces
- by ehdv
Is there a way to write interface-based code (i.e. using interfaces rather than classes as the types accepted and passed around) in C# without giving up the use of things like implicit casts? Here's some sample code - there's been a lot removed, but these are the relevant portions.
public class Game
{
public class VariantInfo
{
public string Language { get; set; }
public string Variant { get; set; }
}
}
And in ScrDictionary.cs, we have...
public class ScrDictionary: IScrDictionary
{
public string Language { get; set; }
public string Variant { get; set; }
public static implicit operator Game.VariantInfo(ScrDictionary s)
{
return new Game.VariantInfo{Language=sd.Language, Variant=sd.Variant};
}
}
And the interface...
public interface IScrDictionary
{
string Language { get; set; }
string Variant { get; set; }
}
I want to be able to use IScrDictionary instead of ScrDictionary, but still be able to implicitly convert a ScrDictionary to a Game.VariantInfo. Also, while there may be an easy way to make this work by giving IScrDictionary a property of type Game.VariantInfo my question is more generally: Is there a way to define casts or operator overloading on interfaces? (If not, what is the proper C# way to maintain this functionality without giving up interface-oriented design?)