By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,975 Members | 1,202 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,975 IT Pros & Developers. It's quick & easy.

cast object to interface

P: n/a
Hi,

Can someone explain the idea behind casting to an interface?

For example:
-> I have an IInterface that contains a Read() method.
-> I have an object "obj" that implements IInterface.

Why would someone do the following and what does it mean?

Object obj = new Object();
IInterface var = (IInterface) obj
var.Read()
Thanks

Nov 29 '05 #1
Share this Question
Share on Google+
15 Replies


P: n/a
You can't do this. Object doesn't implement IInterface. The type that
you create has to implement that interface (agree to the contract, in a
sense), in order for the cast to succeed.

You can't just cast any type to any other arbitrary type successfully.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

<mr********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Hi,

Can someone explain the idea behind casting to an interface?

For example:
-> I have an IInterface that contains a Read() method.
-> I have an object "obj" that implements IInterface.

Why would someone do the following and what does it mean?

Object obj = new Object();
IInterface var = (IInterface) obj
var.Read()
Thanks

Nov 29 '05 #2

P: n/a
> Hi,

Can someone explain the idea behind casting to an interface?

For example:
-> I have an IInterface that contains a Read() method.
-> I have an object "obj" that implements IInterface.
Why would someone do the following and what does it mean?

Object obj = new Object();
IInterface var = (IInterface) obj
var.Read()
Thanks


Assuming that "Object obj = new Object();" really means "SomeObjectThatImplemetsIInterface
obj = new SomeObjectThatImplemetsIInterface();", there really is no point,
that I can think of, in casting to IInterface. If it is true that SomeObjectThatImplemetsIInterface
implements IInterface then you c(w)ould just call obj.Read();

My guess is that the code was written by an inexperienced programmer. Please
correct me if I'm wrong.

Chris
Nov 29 '05 #3

P: n/a
Normally, if you have objects that support interface "IInterface", your
member variable will be defined as type "IInterface" also. However,
you will most likely use reflection (either directly or via a class
factory) to create your IInterface object, and reflection returns
references to type object because it cannot pass back a specific type
reference. At some point, that object reference must be cast to the
interface. Reflection allows you to programmatically create types that
you may not even know about at compile time.

Nov 29 '05 #4

P: n/a
Base classes are useful for polymorphic behavior and as a transport
mechanism.
For polymorphic behavior one might create a collection of references of
type
IMyInterface. For transport one might pass a reference (variable) of
type object.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 30 '05 #5

P: n/a
Hi,

Check out my article, it might be helpful.

http://www.developersdex.com/gurus/articles/739.asp

Happy Coding,

Stefan
C# GURU
www.DotNETovation.com

"You always have to look beyond the horizon and can never be complacent
-- God forbid we become complacent."

Jozef Straus

*** Sent via Developersdex http://www.developersdex.com ***
Nov 30 '05 #6

P: n/a
Sorry if I was a little vague. Here's the code from the book:

interface IStorable
{
void Read();
void Write(object);
int Status {get; set; }
}
public class Document : IStorable
{
public void Read() {...}
public void Write (object obj) {...}

public int Status {
get { return status;}
set { status = value; }
}
.....
}

-------

Then here is my question:

Document doc = new Document("Test Document");
doc.status = -1;
doc.Read();
IStorable isDoc = (IStorable) doc;
isDoc.Status = 0;
isDoc.Read();

Why would someone cast an object to an interface? Instead of
isDoc.Status, can't we just use doc.Status ? This is all very confusing
to me because I'm not quite sure what the purpose is for interfaces. I
understand interfaces are contracts and contains no implementations.
But why would someone want do the casting stated above? I'm kind of
stuck right now in the book because I'm worried I might be missing a
very important concept here which might be used later on; therefore I
would like to get all this cleared up now.

Thanks for all your help!
-----------

Nov 30 '05 #7

P: n/a
Hi Chris,

That's what I was thinking. What is the need for var.Read() when you
can just call obj.Read().

Nov 30 '05 #8

P: n/a
"methodios" <mr********@gmail.com> a écrit dans le message de news:
11**********************@g14g2000cwa.googlegroups. com...

| Why would someone cast an object to an interface? Instead of
| isDoc.Status, can't we just use doc.Status ?

In the given example, yes you could do just that, but interfaces are
designed, amongst other things, to allow commoin behaviour across
hierarchies. IOW, you dont have to derive all your classes from one base
class to get a common behaviour. It also allows you to "derive from"
(implement) more than one interface.

So, you can not only have Document implement IStorable, but any other class
that you desire to have the Read, Write and Status behaviour. Thus I can
then have a list of IStorable items and treat them all the same, regardless
of what their real class is.

Also, I can implement the interface explicitly, thereby setting the
properties and methods to be essentially private to clients of the class.

public class Document : IStorable
{
void IStorable.Read() {...}
void IStorable.Write (object obj) {...}

public int IStorable.Status
{
get { return status;}
set { status = value; }
}
...
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Nov 30 '05 #9

P: n/a
"Joanna Carter [TeamB]" <jo****@not.for.spam> a écrit dans le message de
news: %2****************@TK2MSFTNGP10.phx.gbl...

Sorry, slight change required :

| public int IStorable.Status
| {
| get { return status;}
| set { status = value; }
| }

should be :

int IStorable.Status
{
get { return status;}
set { status = value; }
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Nov 30 '05 #10

P: n/a
Its looks like you are reading that C# book from O'Reilly as I have
that same example in my book. In your last sample code that you posted
I don't see the benefit of casting doc to ISorable interface.
Polymorphism is not acheived here. However, Its seems like the author
is just casting to IStorable as a test to see if doc implements the
IStorable interface. Again, the way shown is not a good way to do it.
I was use the "as" keyword.

Nov 30 '05 #11

P: n/a
"tdavisjr" <td******@gmail.com> a écrit dans le message de news:
11**********************@o13g2000cwo.googlegroups. com...

| Its looks like you are reading that C# book from O'Reilly as I have
| that same example in my book. In your last sample code that you posted
| I don't see the benefit of casting doc to ISorable interface.
| Polymorphism is not acheived here. However, Its seems like the author
| is just casting to IStorable as a test to see if doc implements the
| IStorable interface. Again, the way shown is not a good way to do it.
| I was use the "as" keyword.

Then you would both end up with a runtime error if there were a problem with
the casting not being supported.

To be safe, you really need to do something like this :

{
IStorable isDoc = (IStorable) doc;
if (isDoc != null)
{
isDoc.Status = 0;
isDoc.Read();
}
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Nov 30 '05 #12

P: n/a
The most important point to address here is that you're not quite sure
of the purpose of interfaces. Forget about the casting thing... it was
just a bad example in the book.

The value of interfaces doesn't come up immediately after you create
the object in question. After all, as you pointed out, you have the
object and you know what class it is, so why do you care about
interfaces at that point in the code? The answer is that you don't: you
have a reference to the object and that reference is declared as the
true type of the object, so you can get at all of the functionality of
the object. (For the pendantic types, yes, I know that that isn't
entirely true: there are circumstances in which you have to cast to an
interface in order to "see" methods and properties defined on that
interface, but this is an introduction, not a comprehensive guide. :-)

Interfaces come into their own when you start storing objects in
composite structures and/or passing them around. Think of it this way.

Let's say that you have a bit of functionality that you want to
implement in a bunch of objects that have no other logical realtionship
between them. IStorable isn't such a bad example. Let's say that you're
writing business software, so you have lots of classes defined like
Supplier, Customer, PurchaseOrder, Invoice, StockItem, and things like
that. All of these classes are stored in database tables somewhere. As
well, you have other classes that are just kind of housekeeping things
that you create, use, and destroy while your programs are running but
don't form part of your company's permanent data store.

OK, now what you want to do is write some sort of central software for
managing writes back to your database, caching, and refreshing the
cache from time to time. However, there's no common ancestor between
all of your "stored" classes: a StockItem and a Customer have nothing
to do with each other, other than the fact that they can be stored in
the database. Here, you have a few choices:

1. Make a common base class like StorableObject and inherit every
storable thing from it. That works great when you have only one
quality, "storable," and that's it. However, what happens when some of
these things, like PurchaseOrder and Invoice, should be "printable"?
Well, you could give them a common ancestor, too, which works until you
end up with something that's "printable" and not "storable". Do you see
how, when you have only single inheritance to work with, embedding all
of this functionality in the class hierarchy starts to create fake base
classes with no purpose other than to offer some tidbit of
functionality, and how that in turn leads to a mess?

2. Teach your central data-managing classes about each "storable"
class. Most likely, each method in the data-managing classes would take
a type of "object" (so, no compile-time type checking here) and would
check the object at run time against all possible storable types of
things to see what it is, then cast it, then call its "Store" method.
So, every time you create a new storable class, you have to go an
modify all of the methods in your data-managing classes. Maintenance
nightmare.

3. Create an interface, and have all of those classes that otherwise
have nothing in common, implement IStorable. Now your data-managing
classes can deal only with objects that implement IStorable. *This* is
the big payoff. It's the ability to write code like this:

public class DataManager
{
WriteCollectionToDatabase(IEnumerable collection)
{
foreach (object o in collection)
{
IStorable storable = o as IStorable;
if (storable != null)
{
storable.Store();
}
}
}
}

Notice that the method _doesn't care_ what kind of object is in the
collection, only that the object implements IStorable and so has a
Store() method. This is the big payoff: the ability to write generic
code that can deal with any object in your class hierarchy that
implements the specific behaviour it needs.

Here are some examples of interfaces I've created for my projects:

IKeyed: objects that implement IKeyed know their own primary keys. This
capability is implemented by many classes across my class hierarchy,
but whether an object knows its own primary key or not has nothing to
do with its place in the inheritance tree. Thus, the behaviour is
defined in an interface.

IHasListViewModel: I have various controls that inherit from
Windows.Forms classes. As such, if I want a class that inherits from a
Panel and a class that inherits from a ListView to have some
functionality in common, I have no choice but to use an interface,
because the class hierarchy is already established by Microsoft. I
can't add functionality to Windows.Forms.Control, for example, so I
have to "add in" functionality to selected of my custom controls using
an interface.

ISelfUpdatingCollection: I have many different kinds of collections
that automatically keep themselves in synch with the database. Each one
of these inherits (logically) from the simple collection class of the
same type, so the self-updating collections can't have any common
ancestor that distinguishes them from collections that don't
self-update. To give you an idea of the class hierarchy, here are some
examples:

SelfKeyedCollection (base class)
StockItemCollection (derived from SelfKeyedCollection)
SelfUpdatingStockItemCollection (derived from
StockItemCollection)
SupplierCollection (derived from SelfKeyedCollection)
SelfUpdatingSupplierCollection (derived from
SupplierCollection)

etc. Now, if I want to tell the world that
SelfUpdatingStockItemCollection and SelfUpdatingSupplierCollection have
some functionality in common, and I want to write methods that can deal
with a SelfUpdating...Collection without caring what type it is, I have
to use an interface, because there's nowhere in the class hierarchy
that I can insert the appropriate common behaviour.

Nov 30 '05 #13

P: n/a
Hi,

Check ou this article it will give a good example of how powerful the
use of polymorphism and the use of interfaces is:

http://www.developersdex.com/gurus/articles/739.asp

Happy Coding,

Stefan

*** Sent via Developersdex http://www.developersdex.com ***
Dec 1 '05 #14

P: n/a
Thank you all for your help!

Dec 2 '05 #15

P: n/a
methodios wrote:
Hi Chris,

That's what I was thinking. What is the need for var.Read() when you
can just call obj.Read().


It is an extremely useful technique. When an object implements an
interface there is a binding contract that the object *must* provide an
implementation for the *entire* behaviour that the interface supports:

interface IPrintable
{
void Render(RenderContext ctx);
PaperType PreferredPaperType{set;}
}

class Ticket : IPrintable
{
// etc
}

The class Ticket *must* implement the method Render *and*
PreferredPaperType. Thus when you do this:

IPrintable printableTicket = new Ticket();
printableTicket.Render(thePrinter);

You have a guarantee that you are accessing the 'printable' behaviour of
Ticket. Now, Ticket could be implemented like this:

interface IScreenViewable
{
void Render(RenderContext ctx)
}

class Ticket : IPrintable, IScreenViewable
{
}

In this case the Ticket can be rendered to the screen too, so the
previous code will make sure that the correct version of Render is
called.

Richard
--
http://www.grimes.demon.co.uk/workshops/fusionWS.htm
http://www.grimes.demon.co.uk/workshops/securityWS.htm
Dec 4 '05 #16

This discussion thread is closed

Replies have been disabled for this discussion.