value of z in structured objects in ABC

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • winzone
    New Member
    • Jan 2009
    • 10

    value of z in structured objects in ABC

    Last time interview, I got this questions for test.
    I would like to know which answer is correct.

    Q: Assume you have a list "ABC" which contains structures of "XYZ". "ABC" has 10 "XYZ" objects in.
    Each structure has only three integers (x,y and z). all x and y have been assigned values and z is zero.
    there is a code snippet as shown below.
    foreach(XYZ obj in ABC)
    {
    obj.z = obj.x;
    obj.z = obj.z * obj.y;
    }

    what value you would expect to see in the structure objects in "ABC" after this ?
    1) All z values in the structure Z will be zero
    2) All z values in the structure Z will be equal to value x
    3) Only the first structure in the list "ABC" will have z values equal to x*y
    4) All z values in the structure Z will be equal to value x * y
  • Subin Ninan
    New Member
    • Sep 2010
    • 91

    #2
    I think it should be option 1?

    Comment

    • Joseph Martell
      Recognized Expert New Member
      • Jan 2010
      • 198

      #3
      Since this is .Net, I believe that the answer is 4. The thought is as follows:

      You said that ABC is a list of structures of XYZ. This is important because it implies that
      1. ABC is a generic collection of XYZ structures. Therefore the foreach statement is valid and no type conversion or boxing/unboxing is necessary.
      2. XYZ is a structure so it is a value type. This means that it cannot be NULL. Therefore it is impossible to have null reference exceptions in this code.


      You also stated that the XYZ structure is composed of only three elements: x, y, and z. All three of these are integers. This also means that null reference exceptions are impossible inside the foreach loop.

      The first assignment statement in the loop assigns z the value of x. The second statement resolves the right-hand side first (z * y) and assigns it to z. Since z has already been assigned the value of x, we can make the logical leap:

      z = x
      z = z * y
      (plus a little algebra magic)
      z = x * y

      So I would choose answer 4, though if I were answering the question in person the fact that the answer says
      All z values in the structure Z will be equal to value x * y
      would make me nervous since the structures are of type XYZ, not Z. That is probably me just over thinking things.

      Comment

      Working...