Even though this is a .NET post, the concept absolutely transfers to classic Delphi as well. The other day, I needed to solve a problem in C#. Given a pseudo-code architecture like this:
class Base {}
class Concrete : Base {}
class Normal
{
public Concrete ConcreteProp { get; set; }
}
and usage like this:
Base prop = new Concrete();
Normal obj = new Normal();
obj.ConcreteProp = prop;
I would receive (rightfully) a compiler error. Now, understand a few points before firing off comments.
- The architecture must remain as-is. The classes above are actually FCL classes which I obviously can't change.
- The usage needs to remain similar to the one shown above. I want to be able to store a reference to any class that descends from Base and use it in Normal.ConcreteProp later on.
- Obviously, I could just throw a typecast in here to make things work, but this is the end-result of the test case. My requirements also dictated usage of Activator.CreateInstance and Reflection. I can't add references and typecasts to things I don't know about, so this must be truly dynamic.
.NET (and Delphi) don't have any concept of dynamic typecasting. So in order to solve the problem, I ended up taking a different approach. By using an extra Activator.CreateInstance to create a new Concrete obejct, I can then use that new object to assign over with no problems. After creating the object, I then copy over all of the base properties to the newly created object. So far, this has worked pretty well. However, it is not without it's downsides. The main drawbacks I see to this approach are:
- I am not using the same object reference I stored, which means more memory usage
- I cannot easily assign all properties from the cached Concrete object to the newly created one. In order to do this fully, I'll have to use Reflection to walk through all of the properties and set them all (if possible). For now, I know which properties absolutely must be assigned, so I just assign those.
Edited to add: OK, so I butchered the problem description in my haste. Mea culpa. I think I just stumbled into one of my own pet peeves.
Here's the actual code that doesn't work in case you're interested:
System.Data.Common.DbDataAdapter adapter = sqlDataAdapter1;
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder();
cb.DataAdapter = adapter;