-
interface
im not sure what "interface does". ive tried finding help in tutorials but cant find anything that explains what it does.
could anyone explain what this code does?
public interface IAnimal {
int Legs { get; set; }
string Walk();
}
public class Dog : IAnimal {
public int Legs {
get {
return 4;
}
set {
}
}
public string Walk() {
return "I want to run";
}
}
-
Re: interface
An interface is a cookie-cutter template of sorts.
It declares methods, properties, but cannot define them.
Interfaces are useful when an application must be created to communicate with other parts of a larger multi-tier or component-model application. They also help enforce code integrity - any class that derives from an interface that does not implement the required functionality will fail at compile time - which immediately alerts the developer that something is missing.
In the code, you posted, if you remove the public string Walk(){} function from the Dog class, and try to compile, the compiler will immediately let you know you have a problem. This is especially useful in large enterprise applications. Obviously, for a single developer, you KNOW are building the whole thing, so you know what needs to be passed to a class, what logic needs to be done and vice versa.
Reading the above paragraph, I assure you will not help - I'm not very articulate on some things. A simple search on 'C# Interfaces tutorial' in google should give you all the help you need.
-
Re: interface
The biggest thing an interface does is states that your class abides by the contract stated in IWhatever.
Code:
public interface IHaveControls
{
ControlCollection Ctl{get;set;}
}
public class Widget : IHaveControls
{
....Implement
}
Code:
void foo(object o)
{
if(o is IHaveControls)
{
IHaveControls iCtl = o As IHaveControls;
foreach(Control ctl in iCtl.Ctl)
{
ctl.BgColor = Color.Black;
}
}
}