C# - Select and use different types of objects in a uniform way

Viewed 153

This is my first time posting here and I'm rather new to programming, so I might not be fully understanding concepts which I intend to make use of such as interfaces or polymorphism.

I'm currently building a little game in which the player can select different types of objects and I'm struggling with coming up with a robust selection system. The way it works now is through an interface, which is implemented by every type of object the player can select.

public interface ISelectable
{
    void DoSomething();
}

Then, this interface is used to call the implemented methods on the current selection based on different events such as mouse clicks or keys pressed.

public class Selector
{
    public ISelectable selection;

    public PerformAction()
    {
        selection.DoSomething();
    }
}

The methods are implemented in different ways depending on the type of object. However, I've come across certain situations where I don't need a type of object to respond to an event, thus not needing to implement the method defined on the interface.

public class ObjectType1 : ISelectable
{
    public void DoSomething() { /*Implemented*/ };
}

public class ObjectType2 : ISelectable
{
    public void DoSomething() { /*Not needed*/ };
}

This has led me to believe that this may not be a correct approach to this. Therefore, I have a few questions:

  • Can my approach be fixed or improved so that it makes more sense and I don't encounter the situation described before again?

  • If not, is there a "correct" or simpler way to do this kind of selection system?

Thank you in advance. I will try to respond as fast as possible if any further clarification is needed.

1 Answers

Why does your ObjectType2 implement the interface ISelectable? You can remove it when it does not need it.

Or if you want a general interface, you can try these interface definitions:

public interface ISomeEmptyInterface
{
}

public interface ISelectable : ISomeEmptyInterface
{
    void DoSomething();
}

Change the selector class:

public class Selector
{
    public ISomeEmptyInterface myObj;

    public void PerformAction()
    {
        if(myObj is ISelectable)
        {
            (myObj as ISelectable).DoSomething();
        }
    }
}

Classes implement the individual interface:

public class ObjectType1 : ISelectable
{
    public void DoSomething() 
    { 
        Console.WriteLine("ObjectType1 is called");
    };
}

public class ObjectType2 : ISomeEmptyInterface
{
    // no any implementation
}

A simple program:

Selector sel1 = new Selector();
sel1.myObj = new ObjectType1();
sel1.PerformAction();
// output "ObjectType1 is called"

Selector sel2 = new Selector();
sel2.myObj = new ObjectType2();
sel2.PerformAction();
// not thing happened

This disadvantage is that your Selector must know what other sub ISomeEmptyInterface interfaces are.

Related