Ritesh
Ritesh

Reputation: 13

Use the abstract class of one project in another c#

I have two projects Project A and Project B.In project B there is a class TC which is an abstract class and in that class there is an abstract method CanSave(). I have added the reference of project A in project B. In project B I want to use the abstract method CanSave as override of Project A. So one way is just simply add the class of Project A as a parent class of Project B and then use it as a override method.But the problem is that there is already a class from which the class of project B is inheriting.So i cannot use it because cannot use multiple base classes. What will be the solution so that I can use the abstract class in the Project B

Snippet Project A public abstract class TC { protected abstract bool CanSave(object parameter); }

Project B public class OP:CM(Already there is a base class) { //Want to use CanSave here }

Any help will be appreciated.

Upvotes: 0

Views: 1569

Answers (4)

j4rey
j4rey

Reputation: 2677

you could create another class(Lets say TTC) in Project B which inherits TC

public class TTC: TC
{
    ...
}

then create an object of TTC in OP class

public class OP:CM
{
    private TTC ttcobject;
    //you can inject it
    public OP(TTC _ttc){
        this.ttcobject = _ttc;
        // or just initialize it here
        // ttcobject = new TTC();
    }

    public bool CanSave(object parameter)
    {
        return ttc.CanSave(parameter;
    }
}

Upvotes: 0

opewix
opewix

Reputation: 5083

It's better to extract CanSave method logic to a static method and use it in both projects. Otherwise you have to keep instance of class TC inside your OP instance

Upvotes: 0

Norfolc
Norfolc

Reputation: 458

Convert your abstract class TC to and interface and then you'll be able to derived from it in class OP:

public interface ITC
{
    bool CanSave(object parameter);
}

public class OP: CM, ITC
{
    public bool CanSave(object parameter) 
    {
        ...
    }
}

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37377

If it's abstract method (without implementation) I would suggest declaring interface. You can inherit from one class, but from multiple interfaces (independently whether you already inherit from class).

Upvotes: 1

Related Questions