[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# Implements/Interfaces

Posted on 2011-04-29
7
Medium Priority
?
645 Views
Last Modified: 2012-05-11
Hi Experts,

I'm trying to teach myself C# after years of VB only programming and I'm running into a pickle understanding Interfaces.

I understand that a class can be declared an interface and that a normal class can just implement that interface (similar to inheritance with the Semi-Colon)
So in my new class all i would need to do is have the appropriate methods.

There are 2 things i dont understand.
1. Why would this be done? Why not just type the methods up ourselves? Pros/Cons?
2. How can this be done for Lists

For #2 my idea is
MyClass x;
x.Add("SomeValue");
x.Remove("SomeOtherValue");

without having a variable in the class like this
x.MyVar.Add();
x.MyVar.Remove();


My Current class looks like:
public struct BaseCardInfo
    {
        public string Text;
        public string ImagePath;
    }

    public class XMLFlashcardDatabase : IList<BaseCardInfo>
    {
        private IList<BaseCardInfo> MyList;

        public int IndexOf(BaseCardInfo item)
        {
            throw new NotImplementedException();
        }

        public void Insert(int index, BaseCardInfo item)
        {
            throw new NotImplementedException();
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException();
        }

        public BaseCardInfo this[int index]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void Add(BaseCardInfo item)
        {
            throw new NotImplementedException();
        }

        public void Clear()
        {
            throw new NotImplementedException();
        }

        public bool Contains(BaseCardInfo item)
        {
            throw new NotImplementedException();
        }

        public void CopyTo(BaseCardInfo[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        public int Count
        {
            get { throw new NotImplementedException(); }
        }

        public bool IsReadOnly
        {
            get { throw new NotImplementedException(); }
        }

        public bool Remove(BaseCardInfo item)
        {
            throw new NotImplementedException();
        }

        public IEnumerator<BaseCardInfo> GetEnumerator()
        {
            throw new NotImplementedException();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }

Open in new window


Trying to set up like:
public static void Main()
        {
            IList<BaseCardInfo> x=new (IList<BaseCardInfo>) XMLFlashcardDatabase;


        }

Open in new window


Errors
Error	1	'System.Collections.Generic.IList<Study_Master.BaseCardInfo>' is a 'type' but is used like a 'variable'	C:\Users\Nathan\Documents\Visual Studio\C#\Study Master\Study Master\Form1.cs	32	40	Study Master
Error	2	Only assignment, call, increment, decrement, and new object expressions can be used as a statement	C:\Users\Nathan\Documents\Visual Studio\C#\Study Master\Study Master\Form1.cs	32	61	Study Master
Error	3	'Study_Master.XMLFlashcardDatabase' is a 'type' but is used like a 'variable'	C:\Users\Nathan\Documents\Visual Studio\C#\Study Master\Study Master\Form1.cs	32	61	Study Master
Error	4	Type expected	C:\Users\Nathan\Documents\Visual Studio\C#\Study Master\Study Master\Form1.cs	32	39	Study Master
Error	5	; expected	C:\Users\Nathan\Documents\Visual Studio\C#\Study Master\Study Master\Form1.cs	32	61	Study Master

Open in new window

0
Comment
Question by:bromy2004
7 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 35491691
1. Why would this be done? Why not just type the methods up ourselves? Pros/Cons?
Ok sure, you'd know the methods were there, but how would other parts of your code know? An interface is a contract and it is used to say, "hey, this class is guaranteed to have these members."

In your example above, because you are implementing the IList interface, anyone using your code can rest assured that your class will have the following properties:

Count
IsReadOnly
Item

and these methods:

Add
Clear
Contains
CopyTo
GetEnumerator
GetEnumerator
IndexOf
Insert
Remove
RemoveAt

This also means that you can cast derived types to the more general interface and still be able to call the same methods. For example, if I created a class called MyTestClass, which implemented IList<string>, then I could do something like the following:


class MyTestClass : IList<string>
{
...
}

Open in new window


class Program
{
    static void Main(string[] args)
    {
        List<string> firstList = new List<string>()
        {
            "alpha",
            "bravo",
            "charlie",
        };

        MyTestClass secondList = new MyTestClass()
        {
            "two fish",
            "red fish",
            "blue fish",
        };

        PrintList(firstList);
        PrintList(secondList);

        Console.ReadKey();
    }

    static void PrintList(IList<string> theList)
    {
        foreach (string item in theList)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine();
    }
}

Open in new window


You'll notice that PrintList doesn't care that I passed in an instance of MyTestClass. It only cares that it received an IList<string>, which it got thanks to an implicit conversion when I passed my MyTestClass instance.

2. How can this be done for Lists
Well you'll have to have something internally that stores the data--how you implement that is up to you. That's the beauty of interfaces: you don't care how something that implements an interface does something internally; you only care that it performs some action. Think about it like this: Do you actually care how your refrigerator makes your food cold, or do you simply care that it does keep your food cold? Your refrigerator could be thought of to implement the IKeepFoodCold interface  = )
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35491819
Both Idle_Mind and myself created interface examples here. They may be of use to you.
0
 
LVL 15

Expert Comment

by:x77
ID: 35492362
I suggest to examine some simple interfaces:

   IFormattable - Alllows   ToString(Format,Provider).  - you can try it with provider = null.
   Icomparable, Icomparable<T>  - allows sort - CompareTo(ByVal obj As Object) As Integer
   IEnumerable, IEnumerable <T> - Allows  ForEach ...
   
0
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
LVL 7

Expert Comment

by:OklahomaDave
ID: 35495321
The basic value of interfaces is to establish a common set of functionality that can be guaranteed available across a broad variety of objects.

Admittedly its an academic example, but think of an interface called IVehicle. It could have methods for TurnOn, TurnOff, Steer(direction), Stop, and Accelerate. Any number of concrete classes could implement this interface, but for widely differing actual objects.

Just a thought, hopefully its helpful.
-David
0
 
LVL 10

Author Comment

by:bromy2004
ID: 35495589
Ok, thanks for clearing that up.

So Inheritance is an Interface where you can't edit the Methods/Properties?
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 2000 total points
ID: 35495859
So Inheritance is an Interface where you can't edit the Methods/Properties?
Inheritance and interfaces are two separate concepts, albeit with some similarities.

Inheritance is the mechanism for extending the functionality of a base class within a child class. While these classes are completely different entities, they should, semantically, be somewhat related. Think of the scenario where you have the following:

public class Employee
{
    public string ID { get; set; }
}

public class Manager : Employee
{
    public string DepartmentName { get; set; }
}

public class HourlyEmployee : Employee
{
    public Manager Supervisor { get; set; }
}

Open in new window


Now, both Manager and HourlyEmployee extend the base class Employee, and as such, each has an inherited member, ID. Even though we guaranteed that both the Manager and the HourlyEmployee both have a member called ID, these two classes are still similar in some way--they are both Employees.

With an interface, you can have two seemingly unrelated classes both implement the same functionality. You may be familiar with the generic classes List<> and Dictionary<>. Whereas a list holds "single" elements within its internal storage, a dictionary holds two pieces of information: a key, and the "single" element. I think you'd agree that these two classes are "a bit" different, yet both implement the ICollection interface.

It will basically come down to your choice in design as to which mechanism you employ.
0
 
LVL 10

Author Closing Comment

by:bromy2004
ID: 35495916
Thanks to all experts, but it was the examples that tipped the favour.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Integration Management Part 2
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Suggested Courses

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question