473,782 Members | 2,664 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
15 26302
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************* *********@o13g2 00...legr oups.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
{
WriteCollection ToDatabase(IEnu merable 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.

IHasListViewMod el: 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.C ontrol, for example, so I
have to "add in" functionality to selected of my custom controls using
an interface.

ISelfUpdatingCo llection: 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:

SelfKeyedCollec tion (base class)
StockItemCollec tion (derived from SelfKeyedCollec tion)
SelfUpdatingSto ckItemCollectio n (derived from
StockItemCollec tion)
SupplierCollect ion (derived from SelfKeyedCollec tion)
SelfUpdatingSup plierCollection (derived from
SupplierCollect ion)

etc. Now, if I want to tell the world that
SelfUpdatingSto ckItemCollectio n and SelfUpdatingSup plierCollection 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(RenderCo ntext ctx);
PaperType PreferredPaperT ype{set;}
}

class Ticket : IPrintable
{
// etc
}

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

IPrintable printableTicket = new Ticket();
printableTicket .Render(thePrin ter);

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

interface IScreenViewable
{
void Render(RenderCo ntext 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
7389
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 channal hosting into IIS. There is a class B which is also available through remoting hosted on IIS on the same URI. B creates new of A inside a function. It succeed and able to create instance of A inside B first time. But it failes in 2nd attempt when...
0
5626
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 object of type System.__ComObject to type System.Data.DataSet. Server stack trace: at servidor.IclaseSvr.prueba2(DataSet ds) at
3
13010
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'. here is the code that I used to create a table and then add columns to it later, later I populate the rows in the table.
8
6512
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
1578
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 after converting to .NET 2.0. Unable to cast object of type 'Oracle.DataAccess.Client.OracleCommand' to type 'System.Data.Common.DbCommand'
0
1631
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 follows: ((StyleSheetProvider)this.Page).GetStyleSheetPath(); Is there some different way of typecasting that needs to be done in vs2005? Thanks in advance.
3
10258
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 'System.String'.
10
2540
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 of type Foo.Bar. Foo.Bar data = (For.Bar)input; Thanks,
9
6405
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 = CType(e.Item.FindControl("edit_name"), TextBox)
1
2347
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 web.config has been updated with the necessary section. Using System.Web.Configuration.WebConfiguration.GetSection(), the config information is returned without any issues when the GetSection is set to an object. When the object is casted explicitly...
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9474
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10308
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10143
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10076
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9939
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7486
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5375
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2870
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.