Solved

Confused about Interface coding example.

Posted on 2008-10-13
17
622 Views
Last Modified: 2010-08-05
Hi, I have the following copied from a page of online book that I'm reading.  Here I'm confused about the usage of Interface, Parsable.  I thought Interface can only be inherited by a class but why can it be used as a variable type here to declare a varialbe and also used to pass a parameter.  Is that right?
private Parsable parser;
public Analyzer(Parsable parser)
And these delcared variables would have methods that haven't be implemented yet, isn't it?  That's where I'm confused.  Appreciate someone clarify that for me, thank you.

Although that would work, theres a better way that yields a
more flexible, and interface-oriented, design: extract an in-
terface called Parsable that contains, for the time being, a
declaration for the ReportItems property getter:
public interface Parsable
{
List<string> ReportItems
{
get;
}
}
Then, we can make DumpFileParser implement the
Parsable interface. Next, we change the Analyzer constructors
parameter from DumpFileParser to Parsable. Last,
we change the parser field in Analyzer from the Dump-
FileParser concrete class to be the Parsable interface that
DumpFileParser now implements. When we try to compile,
the compiler might tell us that were using some methods not
defined on the Parsable interface. Well need to add those
methods to the interface as well:
public DumpFileParser : Parsable
{
xxxxxxx
}
public class Analyzer
{
private Parsable parser;
private List<string> reportItems;
public Analyzer(Parsable parser)
{
this.parser = parser;
}
xxxxxxxx
}
None of the existing consumers of Analyzer has to change,
and yet, we have just made Analyzer easier to test and reuse.
If we wanted to add the ability to parse another file format,
Analyzer itself wouldnt have to change to accommodate the
extra functionalityonly the consumers would by passing in
a new class that implemented the Parsable interface.
0
Comment
Question by:lapucca
  • 9
  • 7
17 Comments
 
LVL 14

Expert Comment

by:Ramuncikas
Comment Utility
Interface just tells implementing classes what they have to implement.

Let's take IThemedControl interface as a sample. It tells implementing classes that they have to implement BackColor and ForeColor properties.

Now in your application (either windows or web) you might have some "service" that applies your defined theme to all controls that implement this interface. The problem is that different controls might have different properties and checking to see if they have BackColor or ForeColor properties would be difficult and resources consuming task.

To make it easier you could cycle through all controls on a form/page to see if they implement this interface and if they do set these properties through interface. And when you declare interface variable that means that it can get reference only to instance of a class that implements this interface. Moreover you can access only properties/methods of this instance that are declared in the interface without knowing the actual type of the instance.

Cheers.
R
// Interface sample

public interface IThemedControl

	{

		Color BackColor

		{

			get;

			set;

		}

		

		Color ForeColor

		{

			get;

			set;

		}

	}
 

// Sample service

public class MyThemeService

	{

		public void Init(Page page)

		{

			foreach (Control ctrl in page.Controls)

			{

				if (ctrl is IThemedControl)

				{

					IThemedControl iControl = ctrl as IThemedControl;

					this.ApplyStyles(iControl);

				}

			}

		}
 

		public void ApplyStyles(IThemedControl themedControl)

		{

			themedControl.BackColor = Color.Black;

			themedControl.ForeColor = Color.White;

		}

	}

Open in new window

0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
An interface provides a means of specifying a contract without specifying the implementation of that contract.

http://www.developer.com/net/csharp/article.php/1482651
0
 

Author Comment

by:lapucca
Comment Utility
I know the definition of an Interface.  According to the definition, I don't see how an Interface can used in code to decalre a variable as in the code I supplied and in the code that Ramu supplied.  I still find that confusing.  I mean, you can't instantiate an Interface.  Interface has to be inherited by a class that would implement its properties and methods, right?  But in either code example, they're used before inherited by any class.  That's the part I'm not getting.  It seems to contradict with the Interface definition.
0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
No you cant instantiate it directly but you can do.

IFoo foo = new Bar()

Providing Bar implements IFoo
You then treat an instance of bar as an IFoo, so you dont care about the concrete implementation just the fact
that it implements IFoo.

This is generally known as polymorphism
http://msdn.microsoft.com/en-us/library/ms173152(VS.80).aspx
0
 

Author Comment

by:lapucca
Comment Utility
Hi Crazy,
I understand your example and it makes sense that Bar is a class that implements an Interface, IFoo.  But in the code I supply, the interface is being used as a Type to pass in paramenter and as private vriable declaration.  There were any class that implemented the Interface.
Also, the same in code supplied by Rambu, IThemedControl, is an Interface that isn't inherited by a class but is directly used as a type for declareing variables typel.  Is this valid?  Is it becuase it only has properties and no methods?
Thanks.
0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
Yes its valid, you can pass around the type same as any other type, interfaces can have methods as well..

Take this made up on the spot...
interface IFoo
{
   void SomeMethod();
}
class Bar :IFoo
{
      void IFoo.SomeMethod()
{
    //do something..
}
}
void DoSomethingThatExpectsIFoo(IFoo foo)
{
      foo.SomeMethod();
}
Then you may use it like so
IFoo foo = new Bar();
DoSomethingThatExpectsIFoo(foo);

Interfaces behave just like any other type in terms of passing them around, you may have a private/static public variable that holds a reference to a class that implements your interface just like you would a class type, pretty much the only real difference is an interface doesnt provide any implementation just the contract...
0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
In Rams example, although the controls may actually have the BackColor / ForeColor properties that the interface requires, they would still have to be implemented explicity by the control.
This is a possible language improvement called Duck Typing that allows an object to be considered as implementing the interface if the signatures match, so its to static typed.

see
http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx
0
 

Author Comment

by:lapucca
Comment Utility
1. In Ramu's code, the class MyThemeService reference the Interface directly (IThemedControl iControl = ctrl as IThemedControl;) and it didn't inherit from the Interface.  Why is that OK to declare IControl and instantiate it from an Interface?
2.  The ApplyStyle method is treating the instantiated Interface object like a valid object and accesing its properties.  
Do you see my confustion here?  Thank you.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 13

Expert Comment

by:crazyman
Comment Utility
1. It only casted it to the interface type, the control would have to implement it that bit just isnt shown as i believe its a built in .net interface that a lot of control implement, there is no intantiation ocurring here as ctrl is already instansiated, it is simply being cast to the interface type.

2.Yes thats fine, it is an object (of type IThemedControl) and yes you can access any properties that are part of the interface only, for instance IThemedControl probably does support .Text or .ClientID so you could get to them through the interface but you could get to ForeColor / BackColor

0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
EDITED FOR SPELLING - BEER AND CODE DONT MIX

1. It only casted it to the interface type, the control would have to implement IThemedControl that bit just isnt shown as i believe its a built in .net interface that a lot of controls implement, there is no instantiation occuring here as ctrl is already instansiated, it is simply being cast to the interface type.

2.Yes thats fine, it is an object (of type IThemedControl) and yes you can access any properties that are part of the interface, for instance IThemedControl probably does not support .Text or .ClientID so you couldn't get to them through the interface but you could get to ForeColor / BackColor

0
 

Author Comment

by:lapucca
Comment Utility
Hahahahaha.....  Nope, I don't think they mix well, hahaha...
Thank you for the explaination.  I didn't see "ctl" as the object that the icontrol is being assiged to.  Thank you.  That explains Ramu's code.  But for the code I copied from that book, that doesn't explain it.  Do you think it's just some of the code are shown here?  Thank you.
0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
Could you clarify the code you dont understand as i cant really work it out from all that ;-)
0
 

Author Comment

by:lapucca
Comment Utility
This is how Parsable is declared:

Public interface Parsable

{

  List<sting> ReportItems

  {

    get;

  }

}

Open in new window

0
 

Author Comment

by:lapucca
Comment Utility
1.  Parsable is an Interface but it's being used to declare a variable  in code below.  How can an interface be used as a Type ?
private Parsable parser;
2.  Parsable is again used as a Type for passing in a parameter to the mehtod Analyzer:
public Analyzer(Parsable parser)

These 2 lines of codes are what I don't understand how the Interface Parsable is being used.  Imean, Parsable is inherited and implemented in DumpFileParser but this class is not used at all in the class Analyyzer.  thank you.

public DumpFileParser :Parsable

{

xxxxxxx

}

public class Analyzer

{

private Parsable parser;

private List<string> reportItems;

public Analyzer(Parsable parser)

{

this.parser =parser;

}

xxxxxxxx

}

Open in new window

0
 
LVL 13

Expert Comment

by:crazyman
Comment Utility
So you implement it like so

class MyClass : Parsable
{
List<string> myList = new List<string>();
public List<string> ReportItems
{
get{return this.myList;}
}
}

then
MyClass c = new MyClass();
Parsable p = c as Parsable; //cast to interface...
List<string> lst= p.ReportItems;

you can then pass p around like any other type, you can assign to variable like any other type...


0
 
LVL 13

Accepted Solution

by:
crazyman earned 500 total points
Comment Utility
1.An interface is a type.

2.This example it isnt being used but it could be.

You could have 3 different parsers, all implement Parsable and the consumer (in this case Analyser ) doesnt care about which actual concrete class you pass to it, it only cares that its Parsable and support the parsable methods
0
 

Author Comment

by:lapucca
Comment Utility
Ah, I didn't know that an Interface can be used as a type to declare a varialbe.  That's what I was confused with.  parser is declare as of type Interface Parsable.  Thank you for the extensive information and explaination.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

763 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

6 Experts available now in Live!

Get 1:1 Help Now