0

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.

divinebovine
  • 168
  • 5
  • 4
    What exactly is your goal? Are you trying to build a code generator that creates that interface as a codefile? Or are you trying to build an interface on the fly inside of running code? Or something else? – Joe Enos Aug 23 '13 at 18:02
  • 1
    I recommend T4 for this. – Federico Berasategui Aug 23 '13 at 18:05
  • @JoeEnos, I added an edit to the original post that hopefully explains my question in more detail. – divinebovine Aug 23 '13 at 19:06
  • If your types look like this, wouldn't it make more sense to write the interface and then create the class at runtime? – svick Aug 23 '13 at 19:54
  • I purposely used a simple object only for illustrative purposes. I plan on my proxy being used generically so there's no way that interfaces can be written for every use case. – divinebovine Aug 23 '13 at 20:01

1 Answers1

1

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.
svick
  • 236,525
  • 50
  • 385
  • 514