Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Difference between the two

Posted on 2011-09-19
4
Medium Priority
?
310 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 40
ID: 36565092
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
ID: 36565179
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 2000 total points
ID: 36565780
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
ID: 36566038
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

610 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