views:

38

answers:

2

I have four different Business objects and each calls its corresponding FillBusinessObject method to fill all the individual object properties one by one. Now I wish to create a common method which should be able to fill each type of business object. I've created a base class from which all business objects inherit but I am not able to figure out how to fill individual object properties from a common method.

Is this possible (if yes, then how) or am I in dreamworld?

P.S. I don't wish to take a different route like LINQ.

+1  A: 

Looks like you're over-complicating things.

You could write a method that fills the part that belongs to a common base-class and then calls a specialize method for each type.

Henk Holterman
Ok.. Do you mean to say it's optimal to go with separate methods for filling each business object?
Dienekes
Optimal in readability, yes.
Henk Holterman
and from a best-practices point of view?
Dienekes
That is the same here. Readability is one of the most important factors for best practices. At this level, little else is applicable.
Henk Holterman
^^ Cool.. thanks!
Dienekes
A: 

How about something like this:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main( string[] args )
        {
            // Create some business objects and ask them to initialize
            // themselves.
            //

            var bo1 = new BusinessObject1();
            var bo2 = new BusinessObject2();

            bo1.Fill();
            bo2.Fill();
        }

        public abstract class BusinessObjectBase
        {
            public int x { get; private set; }

            public virtual void Fill()
            {
                x = 123;
            }
        }

        public class BusinessObject1 : BusinessObjectBase
        {
            public int y { get; private set; }

            public override void Fill()
            {
                // Let base class fill itself.
                base.Fill();

                // Now we fill our own properties.
                this.y = 456;
            }
        }

        public class BusinessObject2 : BusinessObjectBase
        {
            public int z { get; private set; }

            public override void Fill()
            {
                // Let base class fill itself.
                base.Fill();

                // Now we fill our own properties.
                this.z = 456;
            }
        }
    }
}
Adel Hazzah
^^ Isn't it somewhat same as what Henk said?
Dienekes