3

Suppose I have a simple class that Adds:

public class Multiply
{
     public int A {get; set;}
     public int B {get; set;}
     public int C {get; set;}

     public List<int> Result {get; set;}

     public void Calculate()
     {
         if (A != 0 && B!= 0 && C != 0)
         {
           Result.Add(A);
           Result.Add(B);
           Result.Add(C);
           Result.Add(A * B);
           Result.Add(A * C);
           Result.Add(B * C);
           Result.Add(A * B * C);
         }
     }
}

The above class models my actual application. I have a series of parameters that get set, in this case A, B and C. I then execute Calculate and use the Multiply object's Result property to access the result.

(There might be a better ways to accomplish this template; Lazy loading comes to mind. If you want to suggest a better template go for it but its not the purpose of my question; its just a simple example that illustrates my question.)

Here is my question:

If I'm using the Object Intializer Syntax:

Multiply m = new Multiplier()
{
   A = 1,
   B = 2,
   C = 3
}

m.Calculate();
DoSomething(m.Result[5]); //DoSomething(6); 

Is there a way to execute Calculate() as part of the m initialization?

2 Answers 2

5

Make Result a read-only property and move the Calculate logic to it.

But no, you can't call methods with initializer syntax. Then it wouldn't be initializer syntax, it would just be some alternative C# syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

I was about to post the same answer.
1

Not as far as I know...

But: you could just do the calculation in the getter for Result.

Edit:

Since someone already posted that, you could also just force the arguments to go into your constructor instead of using the initialization block.

This is actually better since you're caching the result. The way your code works, you can change A,B, and C at any time, but the cached value doesn't change. By encapsulating those attributes and only putting them in the constructor, you prevent your object from falling into an inconsistent state, and you can put whatever code you want in the constructor.

1 Comment

And it took you 4 minutes to post that answer? At least check before writing a duplicate answer. That gets old fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.