Solved

Difference between the two

Posted on 2011-09-19
4
299 Views
Last Modified: 2012-05-12
Consider the following code
public interface A1
{
     string ConvertToString(Object obj);
}

public class A : A1
{
    public string ConvertToString(Object obj)
    {
        string outputString;
        if (obj == null)
        {
            outputString = Convert.ToString(obj);
        }
        else
        {
            outputString = obj.ToString();
        }
        return outputString;
    }
}

Open in new window


Now create the instance of the class

A objectA = new A();
object x = null;
objectA.ConvertToString(x);

Open in new window


Again create the instance of  interface
A1 objectA = new A();
object x = null;
objectA.ConvertToString(x);

Open in new window


My query is what is the difference between the two and under which scenarios the we can use both.
0
Comment
Question by:KaranGupta
4 Comments
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
You cannot create an instance on an interface, because an interface does not contain any member. An interface is just a series of declarations, with no code and no variables.

An interface is used when you need to force many different classes to have a specific set of methods, so that you can use any of those classes in a given context.

Take for example the IList interface that is very often encountered in the framework. The interface is simply a list of methods and properties (Add, Clear, Remove, Count...). The list only, with the types and parameters to pass, but no code.

Almost all the collections and array implement that interface. Look at the declaration for ArrayList in the documentation:

public class ArrayList : IList, ICollection, 
      IEnumerable, ICloneable

Open in new window


A class that implements the interface must have all the specified methods and properties. Otherwise, the compiler will generate an error that such or such method is missing or does no have the right declaration.

ArrayList implements IList, as you can see in its declaration, so it has all the properties and methods required by that interface.

On the other hand, a lot of objects (ComboBox, DataGridView) have a DataSource property, that you can you can use to automatically fill the control with an object with only one line of code Control.DataSource = Object. The only condition is that the object must implement the IList interface.

That means that if you assign an ArrayList to a DataSource, the control will automatically fill with the content of the array.

What happens in the background? The control that has a DataSource property calls the methods defined by the interface in order to get the necessary information to work with the object. The compiler knows that DataSource requires an object that implements IList, and has checked that the object has all the proper methods. So we are sure that the DataSource will be able to retrieve the information it needs in order to automatically manipulate the object.

Another example, always with the ArrayList. It also implements IEnumerable. That means that you can use it in a for each loop. An object that implements IEnumerable has to have a GetEnumerator method. for each calls that method in each loop, and it is up to the class to return the following element. Any object that implements GetEnumerator has that method, so any object that implements IEnumerable can be used in a for each.

The first interface was used to fill controls, the second one for a specific type of loop. The interface did not do anything. It is simply a convention (some call it a contract) that classes needs to fulfill if they want to be used in those contexts.
0
 
LVL 13

Expert Comment

by:Naman Goel
Comment Utility
When you are creating an object of A1(Interface) you can assign any object of class that implements Interface A1 and in case of object of A(class) you can not assign any other class instance.

after assignment of instance of class(A) A1 object will behave in same was as object of A. so there will be no difference as such

 
public interface A1 { string ConvertToString(Object obj);}

    public class A : A1
    {
        public string ConvertToString(Object obj) { string outputString; if (obj == null) { outputString = Convert.ToString(obj); } else { outputString = obj.ToString(); } return outputString; }}

        public class A2 : A1
        {
            public string ConvertToString(Object obj) { string outputString; if (obj == null) { outputString = Convert.ToString(obj); } else { outputString = obj.ToString(); } return outputString; }
        }

Open in new window


  A objectA = new A(); object x = null; objectA.ConvertToString(x);

 A1 objectA1 = new A(); object x1 = null; objectA1.ConvertToString(x);


objectA1 = new A2(); object x2 = "hello"; objectA1.ConvertToString(x2);
0
 
LVL 2

Accepted Solution

by:
yogsoft earned 500 total points
Comment Utility
Interfaces are to be used to enforce contract on classes implemeting it. Still classes can have other public methods.

Example:

public class A : A1 {

    public string ConvertToString(Object obj)
    {
        string outputString;
        if (obj == null)
        {
            outputString = Convert.ToString(obj);
        }
        else
        {
            outputString = obj.ToString();
        }
        return outputString;
    }
    
    public int ConvertToInt(string id)
    {
        int outputInt = 0;
        if (!string.IsNullOrEmpty(id))
        {
            outputInt = Convert.ToInt32(id);
        }
        return outputInt;
    }


}

Open in new window


Using A objA = new A();   user can access ConvertToInt method, where as if you instantiate A as A1 objA1 = new A();  only ConvertToString method.
0
 
LVL 8

Expert Comment

by:crysallus
Comment Utility
With your small snippet of code, the difference is practically speaking, negligible. Though to clarify, in the second example, you aren't creating an instance of the interface A1, you are creating an instance of the object A, but assigning that to a variable with the type of the interface A1.

But more generally, if you are doing things a bit more interesting than in your example, the second approach (using the interface as the variable type), gives you the benefits of polymorphism
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now