Reputation: 61
I have the code and getting the error shown above. But the Class is defined as abstract, so I shouldn't need a code body.
public abstract class Endian
{
public short ToInt16(byte[] value, int startIndex)
{
return unchecked((short)FromBytes(value, startIndex, 2));
}
public int ToInt32(byte[] value, int startIndex)
{
return unchecked((int)FromBytes(value, startIndex, 4));
}
public long ToInt64(byte[] value, int startIndex)
{
return FromBytes(value, startIndex, 8);
}
// This same method can be used by int16, int32 and int64.
protected virtual long FromBytes(byte[] buffer, int startIndex, int len); // << Error here
}
Upvotes: 0
Views: 2847
Reputation: 35318
The virtual
modifier is used to indicate that the method can be overridden in a derived class but needs to be defined in the base class (i.e. by giving it a method body). You want to use the abstract
modifier instead of virtual
, as the error message indicates, which means that the method must be overridden.
Methods that are abstract must have the abstract
modifier even though the class is already marked abstract
in order to clearly differentiate them, and they cannot contain a method body (just a semicolon at the end). It's just the rule and it is what it is.
Upvotes: 4
Reputation: 7903
But the Class is defined as abstract, so I shouldn't need a code body.
Why would you expect that?
protected virtual long FromBytes(byte[] buffer, int startIndex, int len);
Method is still marked as virtual, it expects a body and can be overriden. You should declare it as abstract if you don't want to add the definition.
Upvotes: 0
Reputation: 7360
To be abstract, a method must be declared as such:
protected abstract long FromBytes(byte[] buffer, int startIndex, int len);
You where declaring it virtual, which means it is a proper method, with an implementation, that can be overridden by derived classes.
Upvotes: 0