0

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;

}
}

2 Answers2

1

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();
        }
    }
}
L J
  • 5,249
  • 3
  • 19
  • 29
  • This can help to decide whether to use interface or abstract class http://stackoverflow.com/questions/1474249/abstract-classes-vs-interfaces – YuvShap Oct 15 '16 at 20:49
-1

We can't talk about overriding a proprety in inheritance, I suppose that you talk about method overriding in that case you can force it by making the parent class abstract or make the class inherit from an interface that contains the methods to be overriden.

  • Actually this is possible to override properties http://stackoverflow.com/questions/8447832/can-i-override-a-property-in-c-how – YuvShap Oct 15 '16 at 20:45