Freigeben über


Overriding an Abstract Property vs. Passing a Parameter

An abstract class may require a value to be passed through the constructor like the following example:

 public abstract class Node
{
    private readonly Uri _uri;

    protected Node(string address, string relativePath)
    {
        _uri = new Uri(Path.Combine(address, relativePath));
    }
}

public class Element : Node
{
    private const string relativePath = "/path";

    public Element(string address)
        : base(address, relativePath)
    {
    }
}

Alternatively, it can require that derived types implement a property or a method that returns that value:

 public abstract class Node
{
    private readonly Uri _uri;

    protected Node(string address)
    {
        _uri = new Uri(Path.Combine(address, RelativePath));
    }

    protected abstract string RelativePath { get; }
}

public class Element : Node
{
    private const string relativePath = "/path";

    public Element(string address)
        : base(address)
    {
    }

    protected override string RelativePath { get { return relativePath; } }
}

The first approach is more suitable for initializing a new instance; since the relative path value is only used once. However, if the value will be used more frequently, the property solution sounds more like it. For example, extending the MessageHeader class:

 public class CustomtMessageHeader : MessageHeader
{
    private const string headerName = "CustomHeader";

    /// <summary>
    /// Gets the name of the message header.
    /// </summary>
    /// <returns>The name of the message header.</returns>
    public override string Name
    {
        get { return headerName; }
    }
}