inheritance of abstract class with static property in C#
<p><strong>Short version:</strong></p>

<p>I have an abstract class A. It has a method that needs to know the value of a static class property that is specific to each subclass. The name and type is the same, just the value can be unique for each subclass.</p>

<p>Can I define this static property in the base class A to be able to access it with methods defined in A, but keeping the property's values of different subclasses unrelated?</p>

<p>Or how would I implement something like that?</p>

<hr>

<p><strong>Long version:</strong></p>

<p>Let's say I have an abstract base class for data models. It has a public property <code>Id</code> (Int32). </p>

<p>I would like to implement a constructor in the base class that generates a new ID based on the last assigned ID for objects of a subclass.</p>

<p>The reason is that the <em>real</em> IDs are assigned automatically by the database, but each data model object already has to have a unique ID when it gets constructed without being written to the database yet. As the database assigns only positive integers as ID, my plan is to assign newly created data model objects a temporary, unique negative ID. As soon as the object gets written, the ID will get changed to the real one.</p>

<p>As I have quite a few different data model classes all deriving from my abstract base class, I thought it would be good to include that functionality there to not duplicate it. But each subclass has to have their own counter that points to the next free negative ID, as the different classes' IDs are unrelated.</p>

<p>So I need a static property in each subclass storing this class' last assigned temporary ID, but the mechanism to assign it is always the same and could be implemented into the abstract base class' constructor. However, I can't access a property from the base class that has to be implemented by the subclasses, which means I have to define it in the base class. But will this static property then be global for all subclasses, which is not what I want?</p>

<p>How can I implement this temporary ID counter the most elegant way?</p>

<p><strong>Simplified code example:</strong></p>

<pre><code>public abstract class ModelBase
{
    public Int32 Id { get; set; }
    protected static Int32 LastTempId { get; set; } = 0;

    public ModelBase()
    {
        Id = --LastTempId;
    }
}


public class Model1 : ModelBase
{
    public Model1 () : base ()
    {
        // do something model1-specific
    }
}

public class Model2 : ModelBase
{
    public Model2() : base()
    {
        // do something model2-specific
    }
}
</code></pre>

<p>If I implement it like this, I fear that for both subclasses <code>model1</code> and <code>model2</code>, the inherited static property <code>LastTempId</code> will be the same instance. But I want a separate counter for each subclass while still using it in the base class constructor.</p>