I'm new to using interfaces so I have a question that will probably be pretty easy for most of you.
I am currently trying to make an interface for a windows form. It looks something like
interface myInterface
{
//stuff stuff stuff
}
public partial class myClass : Form, myInterface
{
//More stuff stuff stuff. This is the form
}
The problem comes when I try to implement it. If I implement with
myInterface blah = new myClass();
blah.ShowDialog();
the ShowDialog() function is now available to it. It makes sense- myInterface is an interface, not a form... but I'm curious how I should go about implementing the interface with a windows form, or if it is even a viable option at all.
Does anyone have any suggestions about how I should go about doing that?
Thanks!
A class or struct that implements the interface must implement all its members. Beginning with C# 8.0, an interface may define default implementations for some or all of its members. A class or struct that implements the interface doesn't have to implement members that have default implementations.
Windows Forms (WinForms) is a free and open-source graphical (GUI) class library included as a part of Microsoft . NET, . NET Framework or Mono Framework, providing a platform to write client applications for desktop, laptop, and tablet PCs.
Perform CRUD Operations Using Entity Framework. First of all, create a Windows Forms App. To create a new app click on file menu > New > New project and select Windows Forms App then click on Next button. ProjectName - Enter your project name in this field.
The Implements statement requires a comma-separated list of interfaces to be implemented by a class. The class or structure must implement all interface members using the Implements keyword.
One way to approach this would be to add ShowDialog to myInterface:
interface myInterface
{
DialogResult ShowDialog();
}
Now, you can call that method on the interface without having to cast.
If you want to get a little more fancy with it, you could create another interface which represents any dialog...
interface IDialog
{
DialogResult ShowDialog();
}
Then make your other interface implement IDialog:
interface myInterface : IDialog
{
//stuff stuff stuff
}
This has the advantage of potentially reusing more code... You can have methods which accept an argument of type IDialog and they don't have to know about myInterface. If you implement a common base interface for all of your dialogs, you can treat the the same way:
void DialogHelperMethod(IDialog dialog)
{
dialog.ShowDialog();
}
myInterface foo = new myClass();
DialogHelperMethod(foo);
interface MyInterface
{
void Foo();
}
public partial class MyClass : Form, MyInterface
{
//More stuff stuff stuff. This is the form
}
Form f = new MyClass();
f.ShowDialog(); // Works because MyClass implements Form
f.Foo(); // Works because MyClass implements MyInterface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With