Class v/s Struct
1.) Class can have default constructor. Struct can only have parametrized constructors.
2.) Class is a reference type whereas Struct is a value type.
3.) Struct can’t inherit or implement whereas class can both implement interfaces and inherit interfaces.
We will start by simple interface implementation. Let’s create an interface with one method.
public interface MyInterface
{
int foo();
}
Now let’s first have a look at a simple class
public class MyClass
{
int a;
}
This class compiles fine. Now let’s implement the interface defined above
public class MyClass: MyInterface
{
int a;
}
Now when you compile this class you will get a compile time error stating that MyInterface.foo() is not implemented in MyClass. If you don’t want to implement foo in MyClass then you must declare MyClass as abstract class. Let’s now look at 2 more scenarios of interface implementation
public class MyClass : MyInterface
{
int a;
public void foo()
{
return a;
}
}
This time the class compiles fine.
In next samples we will be discussing about interface polymorphism.