• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 648
  • Last Modified:

Confused about Interface coding example.

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
lapucca
Asked:
lapucca
  • 9
  • 7
1 Solution
 
RamuncikasCommented:
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
 
crazymanCommented:
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
 
lapuccaAuthor Commented:
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
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
crazymanCommented:
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
 
lapuccaAuthor Commented:
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
 
crazymanCommented:
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
 
crazymanCommented:
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
 
lapuccaAuthor Commented:
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
 
crazymanCommented:
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
 
crazymanCommented:
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
 
lapuccaAuthor Commented:
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
 
crazymanCommented:
Could you clarify the code you dont understand as i cant really work it out from all that ;-)
0
 
lapuccaAuthor Commented:
This is how Parsable is declared:

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

Open in new window

0
 
lapuccaAuthor Commented:
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
 
crazymanCommented:
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
 
crazymanCommented:
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
 
lapuccaAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

  • 9
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now