Polymorphing brushes

  • Thread starter Thread starter John Baro
  • Start date Start date
J

John Baro

I have declared a brush i.e.

Brush FillBrush;

later

FillBrush = new SolidBrush(....

everything is set in the constructor and then I use the brush to paint.

later

FillBrush = new LinearGradientBrush(...

FillBrush.InterpolationColors = ....

this does not work. It says that InterpolationColours is not defined etc...
Intellisense only shows up the methods, none of the properties, and only the
methods derived from brush.

I thought this should work?
TIA
JB
 
John... The compiler is enforcing the type of the reference FillBrush
which is
Brush. The object is of class LinearGradientBrush on the heap, but the
variable FillBrush contains a reference of type Brush.
InterpolationColors is
not a valid method of the type Brush.

http://www.geocities.com/jeff_louie/OOP/oop6.htm

Regards,
Jeff
Brush FillBrush = new LinearGradientBrush(...

FillBrush.InterpolationColors = ....<
 
The reason you can't do it has been explained perfectly by Jeff Louie.

What is the value of polymorphism here ? The main idea behind
Polymorphism being the opposite of what you're doing : being able to
consider various objects as being of the same type (while they are not, but
simply have common attributes and behaviors to allow catching their
similarities) ... here you are trying to deal with dissimilarities through
the common interface ...

If you really having some compelling reasons (I wonder what that could
be) that doesn't show here, you can cast to the specific type before
assigning to the properties :
((LinearGradientBrush)FillBrush).InterpolationColors = ...

A more normal and meaning use of polymorhism would look more like :

SolidBrush solidBrush1 = new SolidBrush(...
//assign whatever you need
DoSomething(sildBrush1);

LinearGradientBrush linGradBrush = new LinearGradientBrush(...
//addign InterpolationColors and whatever else you need
DoSomething(linGradBrush);

....

void DoSomething(Brush fillBrush)
{
// code that can apply to any Brush ...
}
 
Thanks for the reply both of you.
What I was doing was reusing the same generic brush for painting gradients
and solid colours.
Cheers
John
 
Back
Top