473,503 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cast object to interface

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
15 26211
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
> 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
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
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
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
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
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
"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
"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
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
"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
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
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
Thank you all for your help!

Dec 2 '05 #15
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
7359
by: Pankaj Jain | last post by:
Hi All, I have a class A which is derived from ServicesComponent to participate in automatic transaction with falg Transaction.Required. Class A is exposed to client through remoting on Http...
0
5590
by: Fidias Gil de Montes | last post by:
In a Distributed Windows application, I receive the following message when the client calls the server: ************** Exception Text ************** System.InvalidCastException: Unable to cast...
3
12944
by: Imran Aziz | last post by:
Hello All, I am getting the following error on our production server, and I dont get the same error on the development box. Unable to cast object of type 'System.Byte' to type 'System.String'. ...
8
6490
by: | last post by:
I have the following class : Public Class MyTreeNode Inherits TreeNode Dim mystring As String End Class Now, when I try to do this : ''''''''''''nodes is a TreeNodeCollection, s is string
0
1557
by: sam | last post by:
Hi: I am not sure if this is the right place to post this question. Please let me know if it is not and I appreciate if someone could point me in the right direction. I am getting this error...
0
1614
by: hlyall1189 | last post by:
Hi, I recently started upgrading some of my old vs 2003 apps to vs 2005 and used the conversion tool but now i get the following error after building the page. I have typecasted the lines as...
3
10240
by: keithb | last post by:
What could be causing this? this code: String Com = ""; if (Com != (String)rw.ItemArray) fails at runtime with the error message: Unable to cast object of type 'System.Int32' to type...
10
2500
by: mypetrock | last post by:
Has anyone run into this error message? Unable to cast object of type 'Foo.Bar' to type 'Foo.Bar'. I'm trying to cast an object of type Foo.Bar that I got out of a hash table into a variable...
9
6372
by: Jim in Arizona | last post by:
I get this error: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlInputText' to type 'System.Web.UI.WebControls.TextBox'. Using this code: Dim test3 As TextBox test3 =...
1
2323
by: =?Utf-8?B?U2NvdHQ=?= | last post by:
Hello, Using VS2008 in a C# web service application, a class has been created that inherits from the ConfigurationSelection. This class file has been placed in the App_Code folder. The...
0
7093
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7287
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5594
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4688
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3177
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3168
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
746
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
399
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.