Follow-up of Is my usage of explicit casting operator reasonable or a bad hack?
One of the users commenting on that question said that it's really bad if the casting operator creates a new object under the hood, as it ceases to be an actual cast. It is of course very valid point.
When one would use the ability of defining custom type conversion? Especially: between two types that are not related by inheritance in any way.
With related objects it makes (some) sense:
class Animal {
public string Name {get;set;}
public int Age {get;set;}
}
class Dog : Animal {
public void Bark(){}
public void Fetch(){}
}
class Cat : Animal {
public void Meow(){}
public void Sleep(){}
}
Although normally casting Cat
to Dog
wouldn't be possible, it makes sense to explicitly allow it - they share all their data, just the behaviour is different.
Even when there would be some difference in fields:
class Parrot : Animal {
public int WingSpan {get;set;}
public void Screech(){}
}
casting still might be desired (Parrot
to Cat
for example, as Cat
doesn't have MORE data than Parrot
).
But what about two types that are not related? It is possible to do:
class Rock{
public int Age {get;set;}
}
and
public static explicit operator Rock(Cat cat){
return new Rock{Age = cat.Age};
}
but why? As pointed out in related question it would cause quite strange behaviour:
var cat = new Cat{Name = "Fluffy", Age = 8};
var rock = (Rock) cat;
rock.Age = 100000000;
Console.WriteLine(rock.Age); // 100000000
Console.WriteLine(cat.Age); // 8
Can anyone give a good example of when implementing explicit operator between unrelated types makes sense and how to do it?