Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Providers - Could I generate a type at compilation-time that decorates all methods of a type somehow?

I've read about the great capabilities of Type Providers, such as static-typing when querying JSON documents, so I can imagine that I can create what I have in my mind at the moment, with this technology.

Let's say I want to allow a consumer of my TypeProvider-library Foo a way to create a type Bar, which will have the following pre-condition for each of their methods: check the mutable state of a boolean disposed field, if it's true, throw an ObjectDisposedException.

Would this be possible? How could one define such an implementation of this high-level type creator?

like image 566
knocte Avatar asked Jul 14 '15 00:07

knocte


People also ask

What is compile time type?

The declared type or compile-time type of a variable is the type that is used in the declaration. The run-time type or actual type is the class that actually creates the object.

When object is created in Java at runtime or compile time?

When is the object created ? Runtime or Compile time ? All objects are created in the Java VM, while it is running. Some objects, like the String shown here, are created in the VM while a class is being loaded, so it's effectively created before your program code runs; but it's still created at "runtime."


1 Answers

A couple of years back Keith Battocchi published a project called ILBuilder. Among other things ILBuilder contains a method type provider in ILBuilder.fs that provides methods for types in mscorlib, e.g.

MethodProvider.Methods.System.Console.``WriteLine : string*obj->unit`

It is possible you could use this as a starting point for a type provider that wraps classes from another assembly and provides methods.

Another option might be to consider Ross McKinlay's Mixin Type Provider that (ab)uses F#'s Type Provider mechanism to provide meta-programming capabilities.

Yet another option might be to use PostSharp, Fody etc. to do IL weaving, or code generation via reflection to build proxy classes.

That said probably the lowest friction solution would be to create a function that checks for disposal and manually add it to each member.

like image 64
Phillip Trelford Avatar answered Sep 21 '22 07:09

Phillip Trelford