Search code examples
c#interfacereflection.emit

Infer interface by type at compile time


Is there any way to infer an interface from an object based on its type. For instance if I had the following object:

public class Person
{
  public string FirstName
  { get; set; }

  public string LastName
  { get; set; }
}

I would like to be able to infer this interface:

public interface IPerson
{
  string FirstName
  { get; set; }

  string LastName
  { get; set; }
}

What I would like to do is be able to create a generic proxy factory, using reflection.emit, that adheres to the inferred interface at compile time. I know that I could instead return a dynamic object with all the object's properties, but that is all handled at runtime vs. compilation.

Edit

A little more explanation for what I'm trying to achieve. I want to create a proxy class that has a method with a signature something like this:

public T GetProxyFor<U>(U SomeObject);

That way a user can call GetProxyFor(People) and get back a PeopleProxy object that would implement the properties of the People object (or any other object). That way, someone using this code could call PeopleProxy.LastName and this would successfully compile, but a call to PeopleProxy.Age would result in an error when compiled since it doesn't exist.

I'm fairly new to Reflection and emitting, so what I'm wanting may not be possible.


Solution

  • Basically, what you're asking for is to execute some code that creates the interface at compile time.

    Your options are:

    1. Use something like T4. You can use that to generate C# code based on some input at compile time.
    2. Use F# type providers. That's basically exactly what you want: it can execute code at compile time and generate the interface right when you write the code that calls GetProxyFor(). But there is nothing like that in C#, so it would require you to switch to F# (at least for the part of your code that uses GetProxyFor()).
    3. Think about the underlying problem behind this question (which you didn't tell us) and solve it in another way.