473,574 Members | 2,749 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Difference between casting to a class and to an interface

lets say we have a 'shape' class which doesn't implement IComparable
interface..

compiler doesn't give you error for the lines below..

shape b= new shape();
IComparable h;
h=(IComparable) b;

but it complains for the following lines
shape b= new shape();
int a;
a=(int)b;

error is Cannot convert type 'shape' to 'int'

is there difference between casting to a class and casting to an interface
?? what does the compiler checks when it is casting to an interface (or does
it check anything ?)

Thanx a lot,

yufufi


Nov 16 '05 #1
7 3657
that is a very good shout.
I was under the impression that you could only cast an object to an
interface if said object implementated said interface.
After having a play I see (like you) that this is not true.
It seems that the compiler does not type check a cast to an interface
(whether this is by design or not I do not know?)
However in the runtime the cast is succeeding.
Unfortunately the methods exposed by the interface will not succeed if
accessed because of the incompatible object type -so when you try and run
one through the interface ...BANG! exception.

I can see this functionality of being of some benefit in some instances, but
I would love to know whether this is by design.

Nice post, well done!

--
Br,
Mark Broadbent
mcdba , mcse+i
=============
"yufufi" <yu****@ttnet.n et.tr> wrote in message
news:OG******** ******@tk2msftn gp13.phx.gbl...
lets say we have a 'shape' class which doesn't implement IComparable
interface..

compiler doesn't give you error for the lines below..

shape b= new shape();
IComparable h;
h=(IComparable) b;

but it complains for the following lines
shape b= new shape();
int a;
a=(int)b;

error is Cannot convert type 'shape' to 'int'

is there difference between casting to a class and casting to an interface
?? what does the compiler checks when it is casting to an interface (or does it check anything ?)

Thanx a lot,

yufufi



Nov 16 '05 #2
If the type of your object is not sealed, the compiler can't know at compile
time whether the actual object implements the "IComparabl e" interface or
not. Remeber, at runtime the variable of type "shape" may point to an object
of a type that is derived from "shape" and implements "IComparabl e".
However - as there is no multiple inheritance - it is not possible that
there is a class that is derived from both "Shape" and "Int".

These are the exact rules, copied from the C# language specification:
"The explicit reference conversions are:
- From object to any other reference-type.
- From any class-type S to any class-type T, provided S is a base class of
T.
- From any class-type S to any interface-type T, provided S is not sealed
and provided S does not implement T.
- From any interface-type S to any class-type T, provided T is not sealed or
provided T implements S.
- From any interface-type S to any interface-type T, provided S is not
derived from T.
- From an array-type S with an element type SE to an array-type T with an
element type TE, provided all of the -following are true:
- S and T differ only in element type. In other words, S and T have the
same number of dimensions.
- Both SE and TE are reference-types.
- An explicit reference conversion exists from SE to TE.
- From System.Array and the interfaces it implements to any array-type.
- From System.Delegate and the interfaces it implements to any
delegate-type. "

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:OG******** ******@tk2msftn gp13.phx.gbl...
lets say we have a 'shape' class which doesn't implement IComparable
interface..

compiler doesn't give you error for the lines below..

shape b= new shape();
IComparable h;
h=(IComparable) b;

but it complains for the following lines
shape b= new shape();
int a;
a=(int)b;

error is Cannot convert type 'shape' to 'int'

is there difference between casting to a class and casting to an interface
?? what does the compiler checks when it is casting to an interface (or does it check anything ?)

Thanx a lot,

yufufi



Nov 16 '05 #3
hey Niki, thanks for that too. Always good to have exact references. Cheers.

--
Br,
Mark Broadbent
mcdba , mcse+i
=============
"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oi******** ******@TK2MSFTN GP12.phx.gbl...
If the type of your object is not sealed, the compiler can't know at compile time whether the actual object implements the "IComparabl e" interface or
not. Remeber, at runtime the variable of type "shape" may point to an object of a type that is derived from "shape" and implements "IComparabl e".
However - as there is no multiple inheritance - it is not possible that
there is a class that is derived from both "Shape" and "Int".

These are the exact rules, copied from the C# language specification:
"The explicit reference conversions are:
- From object to any other reference-type.
- From any class-type S to any class-type T, provided S is a base class of
T.
- From any class-type S to any interface-type T, provided S is not sealed
and provided S does not implement T.
- From any interface-type S to any class-type T, provided T is not sealed or provided T implements S.
- From any interface-type S to any interface-type T, provided S is not
derived from T.
- From an array-type S with an element type SE to an array-type T with an
element type TE, provided all of the -following are true:
- S and T differ only in element type. In other words, S and T have the
same number of dimensions.
- Both SE and TE are reference-types.
- An explicit reference conversion exists from SE to TE.
- From System.Array and the interfaces it implements to any array-type.
- From System.Delegate and the interfaces it implements to any
delegate-type. "

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:OG******** ******@tk2msftn gp13.phx.gbl...
lets say we have a 'shape' class which doesn't implement IComparable
interface..

compiler doesn't give you error for the lines below..

shape b= new shape();
IComparable h;
h=(IComparable) b;

but it complains for the following lines
shape b= new shape();
int a;
a=(int)b;

error is Cannot convert type 'shape' to 'int'

is there difference between casting to a class and casting to an interface ?? what does the compiler checks when it is casting to an interface (or

does
it check anything ?)

Thanx a lot,

yufufi




Nov 16 '05 #4
Nice, but then I have another question..

In generics you can check the type of the input like this:

class Box<T>: where T:IComparable

but compiler gives an error at compile time if you try to create Box
instance of type shape.

On the other hand if you try

class Box<T>
{
public int Compare(T inp1,T inp2)
{
return ((IComparable)i np1).CompareTo( inp2);
}
}

it compiles very well ??

Thanx,

yufufi

"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oi******** ******@TK2MSFTN GP12.phx.gbl...
If the type of your object is not sealed, the compiler can't know at compile time whether the actual object implements the "IComparabl e" interface or
not. Remeber, at runtime the variable of type "shape" may point to an object of a type that is derived from "shape" and implements "IComparabl e".
However - as there is no multiple inheritance - it is not possible that
there is a class that is derived from both "Shape" and "Int".

These are the exact rules, copied from the C# language specification:
"The explicit reference conversions are:
- From object to any other reference-type.
- From any class-type S to any class-type T, provided S is a base class of
T.
- From any class-type S to any interface-type T, provided S is not sealed
and provided S does not implement T.
- From any interface-type S to any class-type T, provided T is not sealed or provided T implements S.
- From any interface-type S to any interface-type T, provided S is not
derived from T.
- From an array-type S with an element type SE to an array-type T with an
element type TE, provided all of the -following are true:
- S and T differ only in element type. In other words, S and T have the
same number of dimensions.
- Both SE and TE are reference-types.
- An explicit reference conversion exists from SE to TE.
- From System.Array and the interfaces it implements to any array-type.
- From System.Delegate and the interfaces it implements to any
delegate-type. "

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:OG******** ******@tk2msftn gp13.phx.gbl...
lets say we have a 'shape' class which doesn't implement IComparable
interface..

compiler doesn't give you error for the lines below..

shape b= new shape();
IComparable h;
h=(IComparable) b;

but it complains for the following lines
shape b= new shape();
int a;
a=(int)b;

error is Cannot convert type 'shape' to 'int'

is there difference between casting to a class and casting to an interface ?? what does the compiler checks when it is casting to an interface (or

does
it check anything ?)

Thanx a lot,

yufufi




Nov 16 '05 #5
Actually I don't know too much about .net generics yet, but I guess they
apply the implicit casting rules here.
After all, the whole fun about generics is that you don't have the runtime
overhead for casting/boxing, and that the code is safer because invalid cast
exceptions are no longer possible, like they used to be in 'pseudo-generic
containers' that used System.Object references everywhere.
If you were allowed to instantiate a "Box<T> where I:IComparable" with a
type T that doesn't implement that interface, all these advantages would be
lost, wouldn't they?

Not sure if that's the whole reason, but it sounds reasonable to me.

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:ur******** ******@TK2MSFTN GP11.phx.gbl...
Nice, but then I have another question..

In generics you can check the type of the input like this:

class Box<T>: where T:IComparable

but compiler gives an error at compile time if you try to create Box
instance of type shape.

On the other hand if you try

class Box<T>
{
public int Compare(T inp1,T inp2)
{
return ((IComparable)i np1).CompareTo( inp2);
}
}

it compiles very well ??

Thanx,

yufufi

"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oi******** ******@TK2MSFTN GP12.phx.gbl...
If the type of your object is not sealed, the compiler can't know at compile
time whether the actual object implements the "IComparabl e" interface or
not. Remeber, at runtime the variable of type "shape" may point to an

object
of a type that is derived from "shape" and implements "IComparabl e".
However - as there is no multiple inheritance - it is not possible that
there is a class that is derived from both "Shape" and "Int".

These are the exact rules, copied from the C# language specification:
"The explicit reference conversions are:
- From object to any other reference-type.
- From any class-type S to any class-type T, provided S is a base class of
T.
- From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T.
- From any interface-type S to any class-type T, provided T is not sealed or
provided T implements S.
- From any interface-type S to any interface-type T, provided S is not
derived from T.
- From an array-type S with an element type SE to an array-type T with

an element type TE, provided all of the -following are true:
- S and T differ only in element type. In other words, S and T have the same number of dimensions.
- Both SE and TE are reference-types.
- An explicit reference conversion exists from SE to TE.
- From System.Array and the interfaces it implements to any array-type.
- From System.Delegate and the interfaces it implements to any
delegate-type. "

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:OG******** ******@tk2msftn gp13.phx.gbl...
lets say we have a 'shape' class which doesn't implement IComparable
interface..

compiler doesn't give you error for the lines below..

shape b= new shape();
IComparable h;
h=(IComparable) b;

but it complains for the following lines
shape b= new shape();
int a;
a=(int)b;

error is Cannot convert type 'shape' to 'int'

is there difference between casting to a class and casting to an interface ?? what does the compiler checks when it is casting to an interface

(or does
it check anything ?)

Thanx a lot,

yufufi





Nov 16 '05 #6
It sounds reasonable to me too , but it also shouldn' allow

class Box<T>
{
public int Compare(T inp1,T inp2)
{
return ((IComparable)i np1).CompareTo( inp2);
}
}
Box<shape> a=new Box<shape>();

I think there is a contradiction here. compiler doesn't give an error here
since shape may be a pointer to a class which is derived from shape and
implements IComparable. But when you use "where T:IComparable" , it doesn't
think maybe I'll pass a class which is also derived from shape and
implements IComparable.
"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oo******** ******@TK2MSFTN GP10.phx.gbl...
Actually I don't know too much about .net generics yet, but I guess they
apply the implicit casting rules here.
After all, the whole fun about generics is that you don't have the runtime
overhead for casting/boxing, and that the code is safer because invalid cast exceptions are no longer possible, like they used to be in 'pseudo-generic
containers' that used System.Object references everywhere.
If you were allowed to instantiate a "Box<T> where I:IComparable" with a
type T that doesn't implement that interface, all these advantages would be lost, wouldn't they?

Not sure if that's the whole reason, but it sounds reasonable to me.

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:ur******** ******@TK2MSFTN GP11.phx.gbl...
Nice, but then I have another question..

In generics you can check the type of the input like this:

class Box<T>: where T:IComparable

but compiler gives an error at compile time if you try to create Box
instance of type shape.

On the other hand if you try

class Box<T>
{
public int Compare(T inp1,T inp2)
{
return ((IComparable)i np1).CompareTo( inp2);
}
}

it compiles very well ??

Thanx,

yufufi

"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oi******** ******@TK2MSFTN GP12.phx.gbl...
If the type of your object is not sealed, the compiler can't know at compile
time whether the actual object implements the "IComparabl e" interface or not. Remeber, at runtime the variable of type "shape" may point to an

object
of a type that is derived from "shape" and implements "IComparabl e".
However - as there is no multiple inheritance - it is not possible that there is a class that is derived from both "Shape" and "Int".

These are the exact rules, copied from the C# language specification:
"The explicit reference conversions are:
- From object to any other reference-type.
- From any class-type S to any class-type T, provided S is a base class of
T.
- From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T.
- From any interface-type S to any class-type T, provided T is not sealed
or
provided T implements S.
- From any interface-type S to any interface-type T, provided S is not
derived from T.
- From an array-type S with an element type SE to an array-type T with

an element type TE, provided all of the -following are true:
- S and T differ only in element type. In other words, S and T have the same number of dimensions.
- Both SE and TE are reference-types.
- An explicit reference conversion exists from SE to TE.
- From System.Array and the interfaces it implements to any
array-type. - From System.Delegate and the interfaces it implements to any
delegate-type. "

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:OG******** ******@tk2msftn gp13.phx.gbl...
> lets say we have a 'shape' class which doesn't implement IComparable
> interface..
>
> compiler doesn't give you error for the lines below..
>
> shape b= new shape();
> IComparable h;
> h=(IComparable) b;
>
> but it complains for the following lines
> shape b= new shape();
> int a;
> a=(int)b;
>
> error is Cannot convert type 'shape' to 'int'
>
> is there difference between casting to a class and casting to an

interface
> ?? what does the compiler checks when it is casting to an interface

(or does
> it check anything ?)
>
> Thanx a lot,
>
> yufufi
>
>
>
>
>
>
>
>



Nov 16 '05 #7
I don't think it's a contradiction;
If you write:
int i = ...;
IComparable comp;
comp = i;
this will compile, as the compiler can check at compile time that it "i"
does imlpement the interface IComparable. However, something like:
object o = ...;
IComparable comp;
comp = o;
will not, as the cast may work at runtime, but doesn't neccessarily.
However, if you use an explicit cast like:
comp = (IComparable) o;
the compiler "assumes" that you know what you are doing, and, as whatever o
points to might well implement ths IComparable interface does not issue an
error.
The main difference is between "static type checking", that is checking the
type of the declared variable at compile time, and "dynamic type checking",
that is checking the type of the referenced object at runtime. Static casts
are the "safer" ones, as they can never fail. So, for implicit casts and
generics "static conversion rules" apply. If you need a runtime type-check,
you have to explicitly use a cast, or an is/as operator. But of course, if
the compiler can tell that a dynamic cast will definitely never succeed
unless the variable points to "null", it can still issue an error.

I'm not really sure if this explanation makes sense to you, but the
compiler's behaviour does make sense to me.

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:uq******** ******@TK2MSFTN GP09.phx.gbl...
It sounds reasonable to me too , but it also shouldn' allow

class Box<T>
{
public int Compare(T inp1,T inp2)
{
return ((IComparable)i np1).CompareTo( inp2);
}
}
Box<shape> a=new Box<shape>();

I think there is a contradiction here. compiler doesn't give an error here
since shape may be a pointer to a class which is derived from shape and
implements IComparable. But when you use "where T:IComparable" , it doesn't think maybe I'll pass a class which is also derived from shape and
implements IComparable.
"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oo******** ******@TK2MSFTN GP10.phx.gbl...
Actually I don't know too much about .net generics yet, but I guess they
apply the implicit casting rules here.
After all, the whole fun about generics is that you don't have the runtime
overhead for casting/boxing, and that the code is safer because invalid cast
exceptions are no longer possible, like they used to be in 'pseudo-generic containers' that used System.Object references everywhere.
If you were allowed to instantiate a "Box<T> where I:IComparable" with a
type T that doesn't implement that interface, all these advantages would

be
lost, wouldn't they?

Not sure if that's the whole reason, but it sounds reasonable to me.

Niki

"yufufi" <yu****@ttnet.n et.tr> wrote in
news:ur******** ******@TK2MSFTN GP11.phx.gbl...
Nice, but then I have another question..

In generics you can check the type of the input like this:

class Box<T>: where T:IComparable

but compiler gives an error at compile time if you try to create Box
instance of type shape.

On the other hand if you try

class Box<T>
{
public int Compare(T inp1,T inp2)
{
return ((IComparable)i np1).CompareTo( inp2);
}
}

it compiles very well ??

Thanx,

yufufi

"Niki Estner" <ni*********@cu be.net> wrote in message
news:Oi******** ******@TK2MSFTN GP12.phx.gbl...
> If the type of your object is not sealed, the compiler can't know at
compile
> time whether the actual object implements the "IComparabl e" interface or > not. Remeber, at runtime the variable of type "shape" may point to
an object
> of a type that is derived from "shape" and implements "IComparabl e".
> However - as there is no multiple inheritance - it is not possible that > there is a class that is derived from both "Shape" and "Int".
>
> These are the exact rules, copied from the C# language specification: > "The explicit reference conversions are:
> - From object to any other reference-type.
> - From any class-type S to any class-type T, provided S is a base class
of
> T.
> - From any class-type S to any interface-type T, provided S is not

sealed
> and provided S does not implement T.
> - From any interface-type S to any class-type T, provided T is not

sealed
or
> provided T implements S.
> - From any interface-type S to any interface-type T, provided S is not > derived from T.
> - From an array-type S with an element type SE to an array-type T with an
> element type TE, provided all of the -following are true:
> - S and T differ only in element type. In other words, S and T
have the
> same number of dimensions.
> - Both SE and TE are reference-types.
> - An explicit reference conversion exists from SE to TE.
> - From System.Array and the interfaces it implements to any array-type. > - From System.Delegate and the interfaces it implements to any
> delegate-type. "
>
> Niki
>
> "yufufi" <yu****@ttnet.n et.tr> wrote in
> news:OG******** ******@tk2msftn gp13.phx.gbl...
> > lets say we have a 'shape' class which doesn't implement

IComparable > > interface..
> >
> > compiler doesn't give you error for the lines below..
> >
> > shape b= new shape();
> > IComparable h;
> > h=(IComparable) b;
> >
> > but it complains for the following lines
> > shape b= new shape();
> > int a;
> > a=(int)b;
> >
> > error is Cannot convert type 'shape' to 'int'
> >
> > is there difference between casting to a class and casting to an
interface
> > ?? what does the compiler checks when it is casting to an

interface (or
> does
> > it check anything ?)
> >
> > Thanx a lot,
> >
> > yufufi
> >
> >
> >
> >
> >
> >
> >
> >
>
>



Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1848
by: Chris | last post by:
I created a control that derives from the System.Windows.Forms.Control namespace. I then created an interface to which this new control must adhere, so that I could require future controls to provide certain functionality. In my form code, I'm not going to be sure of what types of controls the form will be using until run-time. So, I...
2
6364
by: cv | last post by:
Hi, I want to create an object from a class I load from an assembly. Then I want to cast that object to a class (an interface) 'known' to the program in order to pass it to other methods that work with that interface. The casting is invalid but I can't see why, as the class I load from the assembly really is of the type I cast it to. ...
0
1592
by: Greg Conely via .NET 247 | last post by:
I am creating a application that will be using plugins. I am doing this so that when I want to let this application work with another type of dbase system, I only have to write\install one plugin, not the entire app. I have created a base interface, it looks like: public interface myModel sub Initialize(byref DisplayPanel) sub Connect()...
2
2161
by: Enrique Bustamante | last post by:
Casting arrays that works on watch and command window but not in code. My application is casting arrays in a way it should work. To test if I was doing something invalid, I wrote a test code that has similar structure of the classes in my application. The test worked fine, the casting I want to do must work. I compared the structure of the...
3
1641
by: JimM | last post by:
I am trying to create a method in VS 2003 that validates an object argument is of the proper type and within a range of values. I am trying to use a Type to define the casting and object type for the validation. But I get and error of "The type or namespace name 't' could not be found (are you missing a using directive or and assembly...
2
2145
by: harvie wang | last post by:
Hi, I want to implement a common Form with special interface, such as MovePoint(double,double). I create a interface first: namespace ABC.Test { public Interface IMyWindowInterface { void MovePoint(double,double); } }
1
240
by: pitdog | last post by:
This may not be the group to post this in. However I will try... I am interested in how the .NET runtime actually handles casting. For instance... This will work if you assume ChildProduct is a derived class of BaseProduct. BaseProduct product= new ChildProduct();
3
2752
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from...
7
2196
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
0
7813
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...
0
8066
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. ...
0
8249
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...
0
6461
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...
0
5305
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...
0
3743
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...
0
3755
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2251
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1350
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.