[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Confused about Interface coding example.

Posted on 2008-10-13
17
Medium Priority
?
636 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
[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
  • 9
  • 7
17 Comments
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 22704553
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
ID: 22704583
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
ID: 22704798
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
Technology Partners: 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!

 
LVL 13

Expert Comment

by:crazyman
ID: 22704909
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
ID: 22705095
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
ID: 22705227
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
ID: 22705273
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
ID: 22705355
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
 
LVL 13

Expert Comment

by:crazyman
ID: 22705419
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
ID: 22705448
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
ID: 22706056
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
ID: 22706152
Could you clarify the code you dont understand as i cant really work it out from all that ;-)
0
 

Author Comment

by:lapucca
ID: 22706363
This is how Parsable is declared:

Public interface Parsable
{
  List<sting> ReportItems
  {
    get;
  }
}

Open in new window

0
 

Author Comment

by:lapucca
ID: 22706418
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
ID: 22706451
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 2000 total points
ID: 22706482
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
ID: 22706601
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

650 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