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?
double d;
, the expression(Int32)x
should IMHO have been defined to convertd
to an integer when it's a finite value with a fractional part of zero, and throw an exception otherwise; other kinds of integer conversion should have used methodsRoundToInt32
,FloorToInt32
, orTruncToInt32
, [and likewise forInt64
]. – supercat May 05 '15 at 18:54Identifier
is actually very opiniated if you'd like to use implicit or explicit there. Implicit might hide some problems i.e. when you reorder parameters and now yourName
string is in yourIdentifier
string. So you lose quite a part of static typing.Making the cast explicit you would have still full static typing with slightly less visual noise.
– Dirk Boer Sep 07 '23 at 16:47DoSomething( new Identifier(value) )
vsDoSomething( (Identifier)value )
DoSomething(value)
rather than either of the noisy conversions. Yes, implicit might hide some problems (which is why it is rarely used), but the explicit gains you nothing over simply calling the ctor. – Telastyn Sep 07 '23 at 23:41