I have a base class called Base. This base class has a method defined as:
protected virtual string GetFormattedAttribute(string propertyName, object propertyValue)
The propertyValue is defined as:
dynamic propertyValue
So different type of values are assigned to it and appropriate methods are called automatically. For example, I have another virtual method in the same base class for DateTime as:
protected virtual string GetFormattedAttribute(string propertyName, DateTime propertyValue)
This works perfectly. Now, I have a dervied class in which I define the same method, which accepts a List<Contact>:
protected string GetFormattedAttribute(string propertyName, List<Contact> contacts)
This, however, is never called and the first method with propertyValue as object in Base is called instead (I’m calling this method with a derived class object). I tried new and override keywords in the derived class method, but that doesn’t work. Any ideas how can I achieve this result?
This has nothing to do with an override. You are creating an overload of
GetFormattedAttribute. If you callGetFormattedAttributeon a variable of typeBaseit doesn’t know about the overload in the derived class, even if the instance in fact is of the derived type.To put it simply: Your overload in the derived class will only be called, of it is being called on a variable of the derived class or a class that derives from it. Because the method is protected, I assume that you call
GetFormattedAttributesomewhere in your base class. In that scenario, it is impossible for you to use the overloadedGetFormattedAttributein the derived class.One way to achieve the result you are looking for would be something like this:
objectparameter in your derived classList<Contact>call that overload, otherwise call the base implementationSomething like this: