Billy
Billy

Reputation: 241

C#: Any tool to automatically generate Interfaces from Classes?

I'm using the Entity Framework and I want to generate an Interface class from each of my Entity classes.

Is there a tool out there that can run through each class do this automatically for me so i don't have to do it one by one?

Upvotes: 1

Views: 475

Answers (2)

Stef Heyenrath
Stef Heyenrath

Reputation: 9830

You can also use ProxyInterfaceSourceGenerator which can generate interfaces + proxy classes for defined classes.

Example:

Given: an external existing class which does not implement an interface

public sealed class Person
{
    public string Name { get; set; }

    public string HelloWorld(string name)
    {
        return $"Hello {name} !";
    }
}

Create a partial interface

And annotate this with ProxyInterfaceGenerator.Proxy[...] and with the Type which needs to be wrapped:

[ProxyInterfaceGenerator.Proxy(typeof(Person))]
public partial interface IPerson
{
}

When the code is compiled, this source generator creates the following:

1. An additional partial interface Which defines the same properties and methods as in the external class.

public partial interface IPerson
{
    string Name { get; set; }

    string HelloWorld(string name);
}

2. A Proxy class

Which takes the external class in the constructor and wraps all public properties, events and methods.

public class PersonProxy : IPerson
{
    public Person _Instance { get; }

    /// code here ...
}

Upvotes: 0

Related Questions