Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get property into abstract class

Tags:

c#

Here's what I have right now:

public abstract class SampleClass
{
    public abstract void ShowAll();
    public abstract void ExecuteById(int id);
    public string sampleString{get;}
}

public sealed class FirstClass : SampleClass
{
    public override string sampleString
    {
        get { return "AA"; }
    }


    public override void ShowAll()
    {
        ......
    }

    public override void ExecuteById(int id)
    {
        ......
    }
}

public sealed class SecondClass : SampleClass
{
    public override string sampleString
    {
        get { return "BB"; }
    }

    public override void ShowAll()
    {
    ......
    }

    public override void ExecuteById(int id)
    {
    ......
    }
}

Now I add a function like this to each of the classes

public void runStoredProcedure(string sampleString)
{
    SQLClass.ExecuteStoredProcedure(sampleString)
}

One of the ways of doing that is to just add this as an abstract to sampleClass and as an ovverride to FirstClass and SecondClass. Altough the only difference is the passing parameter (samplestring).

The question: is it possible to place this function somewhere(probably in SampleClass) and pass overriden string to this function from First/Second classes to avoid overhead?

like image 666
user194076 Avatar asked Jun 07 '26 22:06

user194076


1 Answers

Yes. What you usually want to do is declare the things that children must define as abstract (so the inheriting classes have to override them). Properties can be abstract too:

public abstract class MyBase {
    public void Execute() {
        Console.WriteLine(MyString);
    }

    // Notice that this has no body, because it is abstract.  Also, I don't need a setter.
    protected abstract String MyString { get; } 
}

public class MyChild : MyBase {
    protected String MyString { get { return "Foo"; } }
}

public class MyOtherChild : MyBase {
    protected String MyString { get { return "Bar"; } }
}

then you can do:

var myChild = new MyChild();

// Prints "Foo"
myChild.Execute();

var myOtherChild = new MyOtherChild();

// Prints "Bar"
myOtherChild.Execute();
like image 163
Chris Shain Avatar answered Jun 10 '26 14:06

Chris Shain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!