foxbot
foxbot

Reputation: 331

Running a method on a runtime-declared class implementing an interface?

So I have an interface, IFormLogger, which contains a method "logData". I have a class which contains this interface and the methods of the interface. My logger, which is designed to be non-dependent on any other classes, has an object, "formOut", which stores a "new class()" which is declared in the other program.

When trying to compile, I get an "'object' does not contain a definition for 'logData', which is understandable."

How do I tell the compiler that the object it will be using has this interface and the method assosciated with it?

Code:

class logger
{
    public enum logOutput { CONSOLE, WINFORM, FILE };
    public enum logLevel { INFO, FINE, WARN, ERR };

    logOutput output;
    object formOut;

public logger(logOutput outputType, object outputForm)
    {
        this.output = outputType;
        if (!(outputForm is IFormLogger))
            throw new ArgumentException();
        else
            this.formOut = outputForm;
    }
public void log(string msg)
    {
        string toLog = String.Format("[{0}][INFO] {1}\n", getTime(), msg);
        if (output == logOutput.WINFORM)
        {
            formOut.logData(toLog);
        }
    }

interface IFormLogger
{
    void logData(string data);
}

In my program.cs file, where the logger is being constructed (cLoggerTest is the name of the form which implements IFormLogger):

logger l = new logger(logger.logOutput.WINFORM, new cLoggerTest());

Upvotes: 0

Views: 45

Answers (3)

Arnaud Develay
Arnaud Develay

Reputation: 3970

You just have to declare formOut as an IFormLogger instead of an object. Since you are already checking for that type in your code, it will not add any new dependency.

Upvotes: 1

Jay
Jay

Reputation: 57919

First, change the object formOut field to IFormLogger formOut and then assign it if/when the argument is of the correct type.

Replace this:

if (!(outputForm is IFormLogger))
    throw new ArgumentException();
else
    this.formOut = outputForm;

with this:

this.formOut = outputForm as IFormLogger;
if (this.formOut == null)
    throw new ArgumentException(/*something useful*/);

Upvotes: 1

SLaks
SLaks

Reputation: 887365

You should declare the field and parameter as IFormLogger, not object.
The compiler will then let you use all members in the interface.

Upvotes: 3

Related Questions