Donavan Wilkens Donavan Wilkens - 1 month ago 14
C# Question

C# Overide Variable

I have a fairly basic question that is probably obvious to most people:

Is this the best way to force a variable to be overridden when the class is inherited?

class foo
{
public abstract int nameOfInt{get; set; }
}

class bar:foo;
{

public bar()
{

override nameOfInt = 0x00;

}
}

L J L J
Answer

If we want to force implementation then interface is the way to go. It tells the inherited object that the rules (methods, properties...) must be implemented.

In case of abstract class we can give basic definitions on how the behavior should be, but we cannot instantiate from an abstract.

Coming to your code:

The property - nameOfInt is named abstract and it is not contained in an abstract class - which is wrong as per the specifications.

This is how you should go about with this:

abstract class foo
{
    public abstract int nameOfInt { get; set; }
}

class bar : foo
{
    public override int nameOfInt
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }
}