[RESOLVED] casting to an interface?
Hi there,
So I was looking at some code regarding the display of XPS documents in XAM,
opening an xps document and setting the source in you DocumentViewer object is easy enough, you just open it and call GetFixedDocumentSequence()
What confuses me is the following - don't understand why they are casting the
Code:
DocumentPaginator myPaginator = ((IDocumentPaginatorSource)myDocumentViewer).DocumentPaginator;
They seem to be casing to an interface and I don't understand why... I don't know that it really matters in day to day life however I figured it was worth asking.
Of course I can clearly see what is going on when you do something like this
Code:
myButton.BackGround = (Brush)this.FindResource("MyBrushResource");
OK - Thanks a lot!
Re: casting to an interface?
Hi r0k3t,
The reason for this class is because they are getting the DocumentPaginator object form a flow document. Im not 100% about the specifics but I believe that when flow documents are casted to objects using this interface they can be paginated as if they where fixed documents.
Re: casting to an interface?
The reason is that the FlowDocument class explicitly implements the IDocumentPaginatorSource.DocumentPaginator property. When a class explicitly implements an interface member, you can only access that member after first casting as the interface type.
As an example, the DataTable class implements the IListSource interface. As a result, you would think that you should be able to do this:
CSharp Code:
var table = new DataTable();
var list = table.GetList();
but that won't compile. You have to do this:
CSharp Code:
var table = new DataTable();
var list = ((IListSource) table).GetList();
That's because the DataTable class explicitly implements the IListSource.GetList method.
Note, a class implementing an interface looks like this:
csharp Code:
public interface ISomething
{
void DoSomething();
}
public class Something : ISomething
{
public void DoSomething()
{
throw new NotImplementedException();
}
}
while the corresponding explicit implementation looks like this:
csharp Code:
public interface ISomething
{
void DoSomething();
}
public class Something : ISomething
{
void ISomething.DoSomething()
{
throw new NotImplementedException();
}
}
Note that you can also implement some members of the interface and explicitly implement others.
Re: casting to an interface?
That makes sense to me I wonder though why would you want to explicitly mark a method like that?
Re: casting to an interface?
Quote:
Originally Posted by
DeanMc
That makes sense to me I wonder though why would you want to explicitly mark a method like that?
Plenty of reading on that topic.
http://www.google.com.au/search?q=ex...ient=firefox-a
Re: casting to an interface?
Sweet - thanks! I also read the msdn link and it made sense. I guess I have never needed to do that... but it is another tool in the toolbox I guess.