Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just have a quick question.

Are constructors used only for assigning data to data fields?

Could I use if statements in constructor or should it be avoided?
I could still use them in the main body of my application I am just not sure what would be better in this situation.

Thank you.




EXAMPLE:

C#
class Calculation
    {
        // every time you use a comboBox you have to create a load event in order to populate it
        public static char[] actors = { '+', '-', '*', '/' };

        decimal x;
        decimal y;
        char actor;
        decimal result;

        public Calculation(decimal _x, decimal _y, char _actor)
        {
            x = _x;
            y = _y;
            actor = _actor;

            // if actor this then result = add() etc...
        }

        public override string ToString()
        {
            return String.Format("{0} {1} {2} = {3}", x, actor, y, result);
        }

        public decimal add()
        {
            return result = x + y;
        }

        public decimal subtract()
        {
            return result = x - y;
        }

        public decimal multiply()
        {
            return result = x * y;
        }

        public decimal divide()
        {
            return result = x / y;
        }
    }
Posted
Comments
TrushnaK 14-Oct-13 9:42am    
Constructor is a member function.You can have if statement in a constructor.

Of course you can! If work needs to be done in the constructor so that data is ready and consistent as soon as an object is constructed, then do it in the constructor.

If it doesn't need to be done, then don't - keep your constructor(s) as short as possible!
 
Share this answer
 
Yes. Do what you need to do.

One of the greatest features of OOP is encapsulation, what happens in a particular method (even a constructor) stays in the method and the caller doesn't need to worry about it.
If putting an if in the constructor allows you to have one constructor rather than have the caller select from several constructors, I'd say that's a good thing.
 
Share this answer
 
You can do this but It is not a good idea to write your business logic in constructor.

The main purpose of the constructor is to initialize local variables when new instance of your class is created.

// if actor this then result = add() etc...

For this line of code you can implement your logic into main class. Or you can create separate method where you accept three parameters :
1. Actor
2. Number1
3. Number2

Regards,
CodeBlack
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900