Naor
Naor

Reputation: 24093

Do inheritance right

I have class:

internal class Stage
{
    public long StageId { get; set; }
    public string StageName { get; set; }
    public int? Order { get; set; }

    public Stage()
    {
        Order = 0;
    }
}

I have also:

public class GroupStage : Stage
{
    private override long StageId { set { StageId = value; } }

    public GroupStage() : base() { }

    public void InsertStage(long groupId)
    {
    }

    public static void SetStageOrder(long stageId, int order)
    {
     ....
    }

    public static void DeleteStage(long stageId)
    {
     ....
    }

    public static GroupStage[] GetStages(long groupId)
    {
     ....
    }
}

and:

public class TaskStage : Stage
{
    public DateTime? Time { get; set; }

    public TaskStage()
        : base()
    {
     ....
    }

    public static Stage GetNextTaskStage(Guid companyId, long taskId)
    {
     ....
    }

    public static Stage[] GetTaskStages(Guid companyId, long taskId)
    {
     ....
    }
}

This is not working and I get the exception: Inconsistent accessibility: base class Stage is less accessible than class GroupStage

I want Stage class to be private and without access except to GroupStage and TaskStage. I also want to make StageId be private in GroupStage and in TaskStage. How can I do that without duplicate the members of Stage in GroupStage and in TaskStage?

Upvotes: 4

Views: 180

Answers (4)

Andrew
Andrew

Reputation: 14457

What you probably actually want is for Stage to be an abstract base class which, therefore, cannot directly be instantiated regardless of its accessibility modifier. Change your definition of Stage:

public abstract class Stage
{
    protected long StageId { get; set; }
    public string StageName { get; set; }
    public int? Order { get; set; }

    protected Stage()
    {
        Order = 0;
    }
}

The protected modifier means that your derived classes will be able to access that member, but it will not be accessible outside those classes.

Upvotes: 1

Paul Alexander
Paul Alexander

Reputation: 32377

You can't make a derived class more accessible than it's base class. What you can do is make TaskStage and GroupStage internal as well, then inherit and expose public interfaces so that only the interface is visible outside of your assembly.

public interface IGroupStage
{
    public string StageName{ get; set; }
    ...
}

interal class GroupStage : IGroupStage
{
...
}

Upvotes: 4

George Stocker
George Stocker

Reputation: 57907

Make it protected instead of private. If you make it protected, you let classes that inherit from it call methods on the base class, and inherit the base class members.

Upvotes: 1

WraithNath
WraithNath

Reputation: 18013

You need to make you Stage class public or protected. if you make it abstract it cant be instantiated on that level, so if its public you dont have to worry about it being created as a base class

Upvotes: 1

Related Questions