Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement custom safe cast (using "as" between arbitrary abstract data structures)?

Today, we have a set of classes that are cast to each other's type when handling data transfers from/to the client. The conversion paradigm is implemented in targets' constructors (i.e. each object knows how to create itself based on the input's type). We intentionally rejected the idea of objects knowing how to convert themselves to the target's type (i.e. each object has a set of ToTypeXyz() methods) as it makes more sense in our case for maintainability purposes.

class ThisType
{
  public ThisType() { ... }
  public ThisType(ThatType input) { ... }
  ...
}

class ThatType
{
  public ThatType() { ... }
  public ThatType(ThisType input) { ... }
  ...
}

I'm thinking of moving out all the conversion logic to centralize all the work. One option is to introduce a utility class with static methods (special case being extension methods for nicer coding experience).

However, it would be extra nice in our case if the conversion could be carried out by safe casting, i.e. using as like the bellow sample. It also would improve performance and decrease the risk of exceptionality, I think.

ThisType input = new ThisType();
...
ThatType target = input as ThatType;

However, when I googled "custom safe cast c#", I got no relevant results, possibly drowning in the noise of standard cases. Is it possible at all?

like image 510
Konrad Viltersten Avatar asked Dec 10 '22 01:12

Konrad Viltersten


1 Answers

Yes, use an implicit / explicit conversion operator:

class ThatType
{
    public ThatType() { ... }
    public ThatType(ThisType input) { ... }
    ...

    public static implicit operator ThatType(ThisType t) => new ThatType(t);
}

With the implicit version above, this will work:

ThisType input = new ThisType();
ThatType target = input;

Although unfortunately the as operator will not work, as it doesn't respect user-defined conversions.

like image 62
Johnathan Barclay Avatar answered Mar 02 '23 00:03

Johnathan Barclay