I am implementing 2 kinds of ByteMessage creater class using Inheritance like below.
abstract class MessageCreater
{
int messageSize;
void validateMessage(byte[] message)
{
if (message.Length!=messageSize)
throw new Exception("Length not proper");
}
}
class XMessageCreater: MessageCreater
{
static readonly int messageSize = 10;
public byte[] Create()
{
byte[] message;
// specific procedure here
validateMessage(message);
return message;
}
}
class YMessageCreater: MessageCreater
{
static readonly int messageSize = 20;
public byte[] Create()
{
// specific procedure here
validateMessage(message);
return message;
}
}
My problem is, to make it short, When validating the message length, messageSize always equals 0 (this is perhaps because the parent class member "messageSize" was being initialized as 0).
when validating in XMessageClass, messageSize variable should be 10, and in YMessageClass, should be 20.
Can you give me a clue to make it work like this? Using Inheritance is not necessary.
CodePudding user response:
The problem is that the fields are completely different for each class, despite the same name. It sounds like you want a virtual property that you can override instead:
abstract class MessageCreator
{
protected abstract int messageSize {get;}
void validateMessage(byte[] message)
{
if (message.Length != messageSize)
throw new Exception("Length not proper");
}
}
class XMessageCreator: MessageCreator
{
override int messageSize {get;} = 10;
public byte[] Create()
{
byte[] message;
// specific procedure here
validateMessage(message);
return message;
}
}
class YMessageCreator: MessageCreator
{
override int messageSize {get;} = 20;
public byte[] Create()
{
// specific procedure here
validateMessage(message);
return message;
}
}