Home > OS >  The program does not return the derived class results
The program does not return the derived class results

Time:08-25

I am writing a script service (ScriptExecuter) which execute scripts. the ScriptExecuter class contains two virtual method ExecuteSQL and CompileCSharp.

Here is the code:

public class ScriptExecuter
{
    public virtual bool ExecuteSQL(string query)
    {
        return false;
    }
    public virtual bool CompileCSharp(string code)
    {
        return false;
    }
}
public class SQLExecuter : ScriptExecuter
{
    public override bool ExecuteSQL(string query)
    {
        return true;
    }

}
public class CSharpCompiler : ScriptExecuter
{
    public override bool CompileCSharp(string query)
    {
        return true;
    }

}

And here is my main method code:

public class Program
{
    static void Main(string[] args)
    {
        var scriptExecuter=new ScriptExecuter();
        var result = scriptExecuter.ExecuteSQL("SELECT * FROM Table1");
        Console.WriteLine(result);
    }

}

The output is false. I want the value of the derived classes.

my question is: How can ScriptExecuter return its derived class return value?

CodePudding user response:

var scriptExecuter=new ScriptExecuter();

You are creating an instance of the base class, if you want an instance of the derived class, you have to create an instance of it.

so replace

var scriptExecuter=new ScriptExecuter();

with

SQLExecuter scriptExecuter = new SQLExecuter();

CodePudding user response:

It does that cause you declared it as the base class ScriptExecuter.

If you change the declaration to ScriptExecuter scriptExecuter=new SQLExecuter();, then, it will still be a ScriptExecuter object but with the SQLExecuter implementation for that method.

E.g. code:

public class Program
{
    public static void Main()
    {
        ScriptExecuter scriptExecuter=new SQLExecuter();
        var result = scriptExecuter.ExecuteSQL("SELECT * FROM Table1");
        Console.WriteLine(result);
    }
}

CodePudding user response:

You have to use the SQLExecuter, if you want the SQLExecuter to be called.

var scriptExecuter =new SQLExecuter();

CodePudding user response:

You need to create an instance of derived class, not base class:

var scriptExecuter= new SQLExecuter

And this is an examply of polymorphism:

ScriptExecuter scriptExecuter = new SQLExecuter();

Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

CodePudding user response:

In your Main Method, You make an instance of ScriptExecuter class and refrence it there. that is your Base class. you have to make instance of your Desired Derived class. other way is to do this:

var scriptExecuter=new SQLExecuter();// you can put any other derived class instead of SQLExecuter() 
  • Related