Method Parameters and OOP

I wrote a method to return the highest value of a specific property of an object. So, I pass by parameter the array (a list of those objects) and works fine. But can I generalize that method? It’s possible to pass by parameter the array and the property that I want to be analyzed? For instance: The objects are cars. In the same method, I can search the oldest year car or the one with more mileage, doing that just passing the property.

Sounds like a job for a proper database and SQL… then the answer would be “yes”

So, you didn’t see something like “Array as Class, Cars as Instance, Mileage as Property” in that beautiful parameter interface? ;/

An array of classes cannot be queried anywhere near as easily as a database table…
and a database record can be equated to a class (or structure)
I’m just offering an alternative… your choice which direction you choose

I think that your best option, if you want to maintain your existing structure, would be to create an Enumeration in the Cars class with a name like “Properties” where you can add values for each of the property names which you want to access. Then you can can call your method something like:

dim maxMileage as integer = GetMaxValue(allCars() as Cars, Cars.Properties.mileage)

In your GetMaxValue method you would use a select case to determine which property you need to access:

select case property case property.mileage // code to get the max mileage property from the array of cars case property.year // code to get the max year property from the array of cars end select

It’s not pretty, but I believe that this is the closest that you will get to your desired functionality.

Thanks for the quick reply, this forum is Unbelievably good!

There is another way to do it, but it’s less pretty. Go with Jared’s suggestion, but you can also use Introspection and provide either the Introspection.PropertyInfo or the property name as a parameter.

That essentially breaks type-checking and I’m offering it here really as a mental exercise only.

I just noticed a little error in that code.
The select case should look like:

select case property case Cars.Properties.mileage // code to get the max mileage property from the array of cars case Cars.Properties.year // code to get the max year property from the array of cars end select

Just in case someone implements a similar code snippet and wonders why it won’t compile.

I would embed the select case in a method of the class where you pass it the enumeration and it returns the value of that property. Both for encapsulation as well as cleaner code.