Shortcut for upcasting to call method...

  • Thread starter Thread starter Jack Addington
  • Start date Start date
J

Jack Addington

I have an method that takes an object that implements 3 interfaces:

iBase
iBaseExt
iBaseExtVisual

I have a method that takes an object of type iBaseExt but sometimes I am
passing in a iBaseExtVisual. If the object is an iBaseExtVisual then I need
to call a method that is only availble to iBaseExtVisual. Right now I am
checking the type, assigning it to a local iBaseExtVisual and then calling
it. I was wondering if there was a way to cast the original parameter to
the type I want and call the method. I'm sure there is a way I just can't
find the syntax.

Here is my basic code

public void save ( iBaseExt ds)
{
iBaseExtVisual dsv = null;

if (ds is iBaseExtVisual)
{
dsv = (iBaseExtVisual)dsv;
dsv.UniqueMethod();
}

ds.genericMethod();

}

I thought I should be able to do something like

if (ds is iBaseExtVisual) (ds as iBaseExtVisual).UniqueMethod();
That being said... is that 'bad form' either or?

thx

jack
 
Jack Addington said:
I have an method that takes an object that implements 3 interfaces:

iBase
iBaseExt
iBaseExtVisual

I have a method that takes an object of type iBaseExt but sometimes I am
passing in a iBaseExtVisual. If the object is an iBaseExtVisual then I need
to call a method that is only availble to iBaseExtVisual. Right now I am
checking the type, assigning it to a local iBaseExtVisual and then calling
it. I was wondering if there was a way to cast the original parameter to
the type I want and call the method. I'm sure there is a way I just can't
find the syntax.

Here is my basic code

public void save ( iBaseExt ds)
{
iBaseExtVisual dsv = null;

if (ds is iBaseExtVisual)
{
dsv = (iBaseExtVisual)dsv;
dsv.UniqueMethod();
}

ds.genericMethod();

}

I thought I should be able to do something like

if (ds is iBaseExtVisual) (ds as iBaseExtVisual).UniqueMethod();
That being said... is that 'bad form' either or?

Well, you end up doing the cast twice, basically. Better would be:

iBaseExtVisual dsv = ds as iBaseExtVisual;
if (dsv != null)
{
dsv.UniqueMethod();
}
 
Jon,

Thanks for the reply... Am I correct in assuming then that if the type
passed in is not iBaseExtVisual, the dsv object won't be instatiated, thus
null, and an exception won't be fired. Thus the check for null is basically
checking if the cast worked ???

thx

jack
 
Jack Addington said:
Thanks for the reply... Am I correct in assuming then that if the type
passed in is not iBaseExtVisual, the dsv object won't be instatiated, thus
null, and an exception won't be fired. Thus the check for null is basically
checking if the cast worked ???

Yup. It means that you don't have to go through the "is" as well as the
cast - it speeds things up.
 
Back
Top