Search code examples
c#object-initializerscollection-initializer

How can you determine if the object initializer is the one calling the Add method?


I have a custom Vector class that can be initialized several ways. It has the following constructor to create a vector of a given length with all zeros.

public Vector(int length) { ... }

or it can use an object initializer by implementing IEnumerable and an Add(..) method like this to fill out a given vector

var v1 = new Vector{ 1, 2, 5 };

The problem lies in the fact that you can write the following code

var v1 = new Vector(3){ 1, 2, 5 };

this looks innocent enough, but it ends up creating a vector of length 6 where the first three values are 0 and then the next 3 are 1,2,5. Ideally this would return just a vector of length 3 with values of 1,2,5. I have gone through and stepped through the object intialization of this and there does not seem to be any indication that the object is being created. It appears as though the constructor runs, and then 3 Add() methods are being called. How can I tell that it is an object initializer calling the Add() method and protect the method from creating additional values?

p.s. As is evident in the comment section the API for this class isn't great as it stands in the question. Still a work in progress, but I appreciate the commentary as it helped me flush out my ideas a little further. I'm leaving the question as is so the comments make sense.


Solution

  • This looks like a design problem. Instead of going around and trying to tell that the compiler is going to invoke your Add method, I would change the Vector constructor to have an overload receiving the actual values, or an array of them:

    public Vector(double x, double y, double z)
    

    Or

    public Vector(params double[] values)
    

    Where the default constructor would hold the default values for the elements without actually adding anything to the underlying array.