Jesse
Jesse

Reputation: 1940

Virtual method being called using base

In regards to a virtual method:

protected internal virtual void PopulateGetParameters(
    int id, List<SqlParameter> parameters)
{
}

Which is being overridden in a class inheriting the base class. What is confusing me is the overriding method is calling back to the the virtual method?

protected override void PopulateGetParameters(
    int id, List<SqlParameter> parameters)
{
    base.PopulateGetParameters(id, parameters);
    parameters.Add(new SqlParameter(this.KeyParamName, id));
}

Seeing as virtual methods are meant to be overridden. What is the purpose of calling base.PopulateGetParameters(id, parameters);? I also can't really find out where the implementation is happening base.PopulateGetParameters is a empty virtual method and the override calls it for some reason.

Upvotes: 1

Views: 185

Answers (2)

dario
dario

Reputation: 5259

The virtual keyword is only used to allow a method to be overridden.

In C#, by default, methods are non-virtual and you cannot override a non-virtual method. This is the opposite of Java, where all methods are virtual by default.

In your case, calling the base implementation of the method, simply does nothing because it's empty. But anyway it's completely fine to call it and actually it's very common.

You can find more informations here.

Upvotes: 2

David Arno
David Arno

Reputation: 43254

A virtual method can be overridden if required. There are no rules against:

(a) Not doing so,

(b) Not calling into the base implementation.

Since in this instance, the base class implementation does nothing, it would be better to create an interface and define PopulateGetParameters there. Then calling base becomes impossible, rather than pointless as it currently is with your example code.

Upvotes: 2

Related Questions