DEV Community

Andreas Jakof
Andreas Jakof

Posted on

Casting to Anything

It has been a while, but I needed some fun and the challenge has been invigorating.

I was working my day to day job and I was changing the signature of a method I was using for logging.

Initially I was using some Type "T" to make a JSON out of it, put it in a wrapper to have some type information as well ... and push it to Application Insights.

Log.Write<T>(ILogger logger, string operationName, T data, 
Exception e = null)
Enter fullscreen mode Exit fullscreen mode

In that special case I needed to make sure, that I always give an ID with the data, which connects the actor and action taken with the log entry.

Nothing easier than that: We just need an Interface, that has the ID as a property and restrict the types on the generic function.

Log.Write<T>(ILogger logger, string operationName, T data, 
Exception e = null) where T : IIdable


public interface IIdable
{
    string Id { get; }
}
Enter fullscreen mode Exit fullscreen mode

Actually, I was using another method to call this one, but you get the gist.

Now the ugly part:
I was using mostly anonymous types for T and (at least according to stack overflow) there was no easy way to implement an Interface in an anonymous type.
There was this answer but he was using Moq and I do not want Moq in Non-Unit-Test-Code.

Don't get me wrong. I like Moq ... for Unit Testing.

But that got me to the idea, that it is possible and that all I needed was a new derived type of my anonymous type, which implements the interface and holds a copy of all the data in the properties.

Challenge accepted

This is what counts for fun to me. Having something I have never done before and where I need to go down to the basement bringing tools.

The beginning was easy. I already created types at runtime having Properties and Backingfields. Like this:

   ...
   public string Name { get; set; }
   ...
Enter fullscreen mode Exit fullscreen mode

What the compiler makes out of this is a private backing field and two methods: get_Name and set_Name. The property itself is just a bit of metadata pointing to those two methods.

And those methods are part of the class. So in the derived type I could use those methods on my new property: the interface wants an Id, the class has a Name? Fine, then get_Id of the derived type just calls get_Name of the base type.

public string Id                // the property the interface wants
{
    get => base.Name;           // get_Id calls get_Name
    set => base.Name = value;   // set_Id calls set_Name
}
Enter fullscreen mode Exit fullscreen mode

Down to the basement

Sadly, you cannot write that in C# for a type you only know at runtime. That only works with IL. So: down to the basement, bring System.Reflection.Emit.

var getter = typeBuilder.DefineMethod("get_Id", ...);
var il = getter.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);              // this
il.Emit(OpCodes.Call, sourceGetter);   // base.get_Name()
il.Emit(OpCodes.Ret);
Enter fullscreen mode Exit fullscreen mode

The first draft went completely wrong, because I had not considered several things.
The second one went better, but only the third one reached a state I was halfway happy with.

After driving out a few more bugs and extending it with a lot of things that came much later, I now have a dangerous tool, that I will NEVER use, but of which I know that it was fun to develop.

Disclaimer:
This tool is highly unsafe and should be used with extreme caution. It can break type safety and lead to unpredictable behavior. Use at your own risk.

Welcome to AnyCast

AnyCast is a collection of extension methods on object. It allows any object of a class to become compatible with an interface (if needed with a mapping), even if its class has never heard of that interface.

Handle with care or leave it be - maybe better.

How it works

  • A subclass of the object's type is generated at runtime, implementing the interface (including all inherited interfaces).
  • The interface properties call the getters and setters of the class's properties (with the same name or as mapped).
  • You always get a copy: all instance fields (including private ones) are copied into an instance of the generated type. It is a shallow copy: referenced objects (lists, child objects, event subscribers, ...) are shared with the original.
  • Generated types are cached per source type, interface, mapping and options.

Usage

First Don't. But if you really really want to ... just for fun and never in any productive environment ... Here's how you can do it.

public interface IIdable
{
    string Id { get; }
}

public class Customer
{
    public string Id { get; set; } = "";
    public string Name { get; set; } = "";
}

var customer = new Customer { Id = "42", Name = "Jane" };

// Same property names: always a copy.
IIdable idable = customer.ToInterface<IIdable>();

// Different property names: map source property -> interface property.
IIdable byName = customer.ToMappedInterface<IIdable>(new PropertyMappingCollection
{
    { nameof(Customer.Name), nameof(IIdable.Id) },
});

// The original if it already implements the interface, otherwise a copy.
IIdable maybe = customer.AsInterfaceOrCopy<IIdable>();
Enter fullscreen mode Exit fullscreen mode

The copy is still a Customer, so (Customer)idable works and shows the copied values.

Options (all of them unsafe)

By default only accessible accessors of compatible types are used. Everything else throws at conversion time with a hint which option would help. If you really want to, you can opt out of the safety nets with InterfaceConversionOptions:

Option Effect
IgnoreAccessChecks Uses private/internal accessors and init-only setters, and non-public types. Bypasses encapsulation and immutability.
CreateMissingSetters The interface wants a setter the class does not have (or cannot be used): the property gets its own backing field on the copy, initialized with a snapshot of the class's value.
CreateMissingGetters Same for getters. Without a usable getter the field starts with default.
var copy = readOnlyThing.ToInterface<IWritable>(InterfaceConversionOptions.CreateMissingSetters);
Enter fullscreen mode Exit fullscreen mode

Initial values for those generated backing fields can be given in the mapping:

var mappings = new PropertyMappingCollection
{
    { "Value", "Value", 42 },   // source, target, initial value
};
Enter fullscreen mode Exit fullscreen mode

If a derived interface redeclares a property with another type (new object Name hiding string Name) and the base declaration cannot be implemented through the redeclaration, it gets its own field as well, just like new hiding in C#. Its initial value can be set with a qualified target: { "Name", "IBase.Name", "init" }.

Limitations

  • Generated types are never unloaded.
  • Types are generated with System.Reflection.Emit: not supported with NativeAOT. With trimming, members only accessed via reflection may be removed.
  • Constructors are not run for the copy; its state comes from the copied fields.
  • Only interfaces consisting of properties: no methods, events or indexers (for now).
  • Only classes that are not sealed. That rules out structs, records declared sealed and, yes, anonymous types: the compiler generates them as internal sealed classes. So the use case that started all of this is exactly the one AnyCast cannot handle. Fun was had nonetheless.

Praise be to the designers of C# or I would have used this in practice. Instead, I replaced all those anonymous objects with one class that wraps the data for me and implements IIdable.

Repository

If you want to have look and toy with it a bit:
https://github.com/DerGuru/AnyCast/

Top comments (0)