Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Interface from existing class

I have a class as:

Class MyClass {    public MyClass { ... }    public string Name { get { ... } }    public int IdNumber { get { ... } set { ... } }    public void GenerateNme {...} } 

It is just a sample class. I wish to generate Interface from it. Like, MyClass is implementing IMyClass interface. I wish the output to be

public Interface IMyClass {    string Name { get; }     int IdNumber { get; set; }     void GenerateNumber(); } 

and

MyClass : IMyClass {  } 

It can be done manually, but I was just curious to know, is there any other simple method to follow to accomplish this? If not clear, leave a comment.

Thanks.

like image 604
Sandy Avatar asked Feb 14 '12 12:02

Sandy


People also ask

Can I create an interface from class?

Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.

How do I extract an interface?

Place your cursor in the class name. Press Ctrl+R, then Ctrl+I. (Your keyboard shortcut may be different based on which profile you've selected.) Press Ctrl+. to trigger the Quick Actions and Refactorings menu and select Extract Interface from the Preview window popup.

Can interface derive from class in C#?

C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.

Can an interface be inherited?

Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.


1 Answers

Yes, you can extract an interface from a class using Visual Studio:

Inside the target class file: Right Click > Refactor > Extract Interface...

Example

enter image description here

then

enter image description here

like image 57
ken2k Avatar answered Sep 19 '22 12:09

ken2k