Jens
Jens

Reputation: 2702

Get derived object from base class object

I am programming a grammar parser for learning purposes and I have problems with inheritance.

var grammars = new Grammar[] { new VariableGrammar() };
this.GrammarRules = new List<Grammar>(grammars);

I create a list of Grammar's, VariableGrammar inherits from Grammar. But in later coding stages there would be many more objects in the list of different types, all of which inherit from Grammar. When I want to access an element I could use a foreach like this:

var grammars = new Grammar[] { new VariableGrammar() };
this.GrammarRules = new List<Grammar>(grammars);

foreach (var grammarRule in this.GrammarRules)
{
    grammarRule.Parse("...");
}

But the problem is that grammarRule is Grammar and not a VariableGrammar. Because of that the Parse method of the Grammar class is called instead of the VariableGrammar class.

The question is: Is there a possibility to access the original object with the right Type in this case VariableGrammar?

I know there is the possibility of casting it, but then I have to write a big code block for every possible cast option.
Another possibility could be using reflection and call the method over this approach but this is not that great either because when I change the method name I have to change it in the reflection too, because I am only able to call the method via the method name as a string.

Upvotes: 1

Views: 492

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

But the problem is that grammarRule is Grammar and not an VariableGrammar.

Actually, it is both, because VariableGrammar derives from Grammar

Because of that the Parse method of the Grammar class is called instead of the VariableGrammar class.

This means that the Parse method in the Grammar class is not marked virtual. Once you mark it virtual and add override to the implementation in VariableGrammar, the problem will be solved.

Upvotes: 2

Related Questions