What is the difference between a class and an interface in C#?

Can you also provide real world examples please!
freezegravityAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
JimBrandleyConnect With a Mentor Commented:
An interface is like a contract established with consumers of a class. For example, say you create an interface called ISupportNameAndAddress as
public interface ISupportNameAndAddress
{
   string   Address {get; set;}
   string   Name {get; set;}
}

Now you create two simple classes as:
public class Person : ISupportNameAndAddress
{
   private string mAddress = string.Empty;
   private string mName = string.Empty;

   public string Address
   {
      get { return mAddress; }
      set { mAddress = value; }

      // Constructors and other code...
   }
}

public class Company : ISupportNameAndAddress
{
   private string mAddress = string.Empty;
   private string mName = string.Empty;

   public string Address
   {
      get { return mAddress; }
      set { mAddress = value; }

      // Constructors and other code...
   }
}

Now say in some third class, you have a method to print mailing labels. You can:
public void PrintMailingLable( ISupportNameAndAddress addressee )
{
   string name = addressee.Name;
   string address = addressee.Address;
   // Now code to use those values...
}

You can pass that method an instance of a Person or a Company, and it doesn't need to care about which it is. You can accomplish the same thing with base classes, but since in .Net a class cannot derive from multiple classes, that can be limiting.

Jim
0
 
Malik1947Connect With a Mentor Commented:
check this out


http://www.csharp-station.com/Tutorials/Lesson07.aspx
http://www.csharp-station.com/Tutorials/Lesson13.aspx

this should explain sufficiently the difference between the two.

0
 
Éric MoreauConnect With a Mentor Senior .Net ConsultantCommented:
an interface has no code, only methods and properties declarations.

it is used to ensure that multiple classes implements the same interface (set of methods and properties)
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
JimBrandleyCommented:
You may notice I did not add the Name property to either of my classes. That would cause a compiler error to remind me that my classes did not fulfill the contract to provide that property. so, If I add:
   public string Name
   {
      get { return mName; }
      set { mName = value; }
   }

To both classes, it will compile.

Jim
0
 
freezegravityAuthor Commented:
I think I mostly understand the difference between the two. I will just have to implement the concepts a few times to really get a hang of it.

THANKS!
0
All Courses

From novice to tech pro — start learning today.