Question

Given the following pseudo C# code:

class BigMessage : Message { }

class SmallMessage : Message { }

abstract class Message
{
    static public Message Factory()
    {
        Random random = new Random();
        int randomNumber = random.Next(0, 100);
        if (randomNumber > 50)
        {
            return new BigMessage();
        }
        else
        {
            return new SmallMessage();
        }
    }
}

class Worker
{
    public void Comprehend(BigMessage bm)
    {
    }
    public void Comprehend(SmallMessage bm)
    {
    }
    public void start() {
        Message msg = Message.Factory();
        Comprehend(msg);
    }
}

If I ask the Factory to give me a random Message object inherited from Message (e.g. Big or Small Message), and I would like the Comprehend methods in the Worker class to act on the type of message given using overloading (the proper OO way, rather than explicit type checking), why do I get the following two types of errors and can you help me understand what I am doing wrong?

  1. The best overloaded method match for 'Worker.Comprehend(BigMessage)' has some invalid arguments.
  2. cannot convert from 'Message' to 'BigMessage'

Ultimately I expect the Factory to provide me with an object inherited from Message, who's type I do not know in advance. I do need to act differently given the different type returned. Inheritance is very helpful in this scenario as the abstract class provides much useful functionality shared with it's child classes.

.NET 4.5 is used.

Thanks in advance!

Was it helpful?

Solution

The reason that you get the conversion error is that you cannot convert a "Message" type to a concrete "BigMessage" or "SmallMessage". It should be the other way around where you have Comprehend(Message msg) and that allows the method to accept any inherited objects.

In addition, what I think you are trying to achieve is polymorphism. I believe to correctly create your objects, your base abstract class Message should have a method called "Comprehend" and in your worker process, you call msg.Comprenhend(). This way, as you get more additional message types, you are not adding additional comprehend methods to your worker class for each message. By leveraging OOP and inheritance, you let the object decide how they comprehend themselves.

sample code below:

abstract class Message
{
  abstract void Comprehend();
  public static Message Factory(){... code here to return message }
}

class BigMessage : Message
{
  public void Comprehend()
  {
    //do work here
  }
}

class SmallMessage : Message
{
  public void Comprehend()
  {
    //do work here
  }

class Worker
{
  public void Start()
  {
    var msg = Message.Factory();
    msg.Comprehend();
  }

}

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top