Ghassan Karwchan
Ghassan Karwchan

Reputation: 3539

C# dealing with derived types, refactoring

I am using a third-part .NET library that has the following classes.

Shape (the abstract base class)

(all the below classes derived from him)

Rectangle

Circle

Triangle

all of these classes has a property called Area

I am going through an array of Shape(s), and set the area

P.S: Area is not a property of the Shape, instead it is a property of each class.

so my code looks like this:

if (shapeVar is Reactangle)
{
   (shapeVar as Rectangle).area = value;
}

if (shapeVar is Circle)
{
   (shapeVar as Circle).area = value;
}

if (shapeVar is Triangle)
{
   (shapeVar as Triangle).area = value;
}

Is there a better way to do this? I feel like it is stupid, but I didn't find other way to do it

I am using .NET 4

Upvotes: 0

Views: 126

Answers (3)

Eranga Dissanayaka
Eranga Dissanayaka

Reputation: 1930

you can wrap Rectangle, Circle and Triangle classes (that come from the third party assembly) and create 3 new classes in your own code.

Then you can have an interface for e.g:

        public interface IShape
        {
            double Area{get;set;}
        }

Make the wrapped classes to implement this common interface.

After that you can use all three of these classes in your code in a common way without having to know what their actual concrete classes are. (by referring to Interface type rather than Shape base type)

Upvotes: 1

Eric H
Eric H

Reputation: 1789

Why not have the Area be a method that returns from the derived type instead of being set?

public abstract class Shape
{
    abstract public double Area();
}

public class Square : Shape
{
    double sideLength;
    public double Area
    {
        return sideLength * sideLength;
    }
}

public class Circle : Shape
{
    double radius;
    public double Area
    {
        return Pi * r * r;
    }
}

If you want to stick to setting the area, you could move your Area into the base class :

public abstract class Shape
{
    public double Area;
}

public class Square : Shape
{
    ...
}

and you look through shapes setting the area based on the derived type you could do :

foreach (Shape shape in shapes)
    switch(typeof(shape))
    {
        case typeof(Square))
        {
            shape.Area = value; //I imagine this is derived type specific
            ...
        }
    }

Upvotes: 0

user694833
user694833

Reputation:

You can use reflection to access the area property of each shape, although there is a small performance cost:

shapeVar.GetType().GetProperty("area").SetValue(shapeVar, value, null);

Upvotes: 2

Related Questions