Baer1987
Baer1987

Reputation: 23

Call an override method in an abstract class

i have a problem. I try to start the override Host method from Program.cs in the abstract class AbstractGenericClass.

public abstract class AbstractGenericClass<T>
{
    protected abstract void Host();

    public static void Start()
    {
        //add additional logic for all classes that use this

        try
        {
            ((AbstractGenericClass<T>) Activator.CreateInstance(typeof(T))).Host();

            Console.WriteLine("Works!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Don't Works!");
        }
    }
} 

class AnotherClass
{
    public void DoSomething()
    {
        //NOP
    }
}

class Program
    : AbstractGenericClass<AnotherClass>
{
    static void Main(string[] args)
    {
        Program.Start();

        Console.ReadLine();
    }

    protected override void Host()
    {
        Console.WriteLine("Host running...");
    }
}

I add here all sample classes i create for showing what i mean. The line with ((AbstractGenericClass) Activator.CreateInstance(typeof(T))).Host(); crash the program because of InvalidCastException. It must be possible to call the Host method but i have no idea how i could this, if this dont operates.

Have you any other idea how this could operate? Or is this totally wrong what i try?

Upvotes: 0

Views: 89

Answers (2)

DSway
DSway

Reputation: 785

You can't cast the result from CreateInstance as AbstractGenericClass because it is of type AnotherClass, which does not derive from AbstractGenericClass and doesn't have a Host method anyway. Sounds like what you want is to get an object of type Program and call Host on that.

Upvotes: 0

Ovidiu
Ovidiu

Reputation: 1407

Replace

((AbstractGenericClass<T>) Activator.CreateInstance(typeof(T))).Host();

with

Host();

Because Host() is an abstract method, Program.Start() will call the implementation of this method in the derived class, so it will execute the implementation of Host() from Program.

Upvotes: 1

Related Questions