473,769 Members | 5,601 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 26300
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.co m

<mr********@gma il.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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 "SomeObjectThat ImplemetsIInter face
obj = new SomeObjectThatI mplemetsIInterf ace();", there really is no point,
that I can think of, in casting to IInterface. If it is true that SomeObjectThatI mplemetsIInterf ace
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 programmaticall y 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********@gma il.com> a écrit dans le message de news:
11************* *********@g14g2 00...legr oups.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.Statu s
{
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************* ***@TK2MSFTNGP1 0.phx.gbl...

Sorry, slight change required :

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

should be :

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

Joanna

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

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
13006
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
1630
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
2539
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
2345
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
9423
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
10045
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...
0
9863
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...
0
8870
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
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
6672
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
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...
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.