2

I have a constructor that has a similar signature to ExampleObject(string name, params object[]).

My usual procedure of passing items to this constructor is:

var thisObject = new ExampleObject("name", obj1, obj2, obj3);

Is there anyway I can initialize a separate array of objects, and pass that array to the constructor IN Addition to how I normally do it, by means of LINQ or some other magic?

Ideal result:

object[] specialObjects = {new object("specObj1"), new object("specObject2")}
var thisObject = new ExampleObject("name", obj1, obj2, specialObjects...

Would I need to use LINQ's Enumerable, ForEach, or something I'm completely unaware of, or is something like this not feasible and I should include obj1 and obj2 into specialObjects?

3
  • @JeffMercado That is assuming the OP has control over the implementation of ExampleObject, which may or may not be the case. Commented Jan 14, 2016 at 19:03
  • I don't, but, good to know that's also an option in the future if I do have control over the implementation. Commented Jan 14, 2016 at 19:27
  • You don't necessarily need access to an class implementation to do what you need. You always have the option to create methods to bundle operations you can't do directly. Create a method that matches your usage pattern and implement it using what's available. Commented Jan 14, 2016 at 19:59

1 Answer 1

2

The params keyword is just syntactic sugar for the creation of an array - you could as well do it with an array literal, i.e.

var thisObject = new ExampleObject("name", new [] {obj1, obj2, obj3});

Once you look at it this way, you realize that it is not possible to use an array for part of the parameter list. You have to create a new array. You could definitely use LINQ. Here is an example:

var thisObject = new ExampleObject("name", 
    (new [] {obj1, obj2}).Concat(specialObjects).ToArray());

(Note that there is a performance penalty involved in using code like this as several temporary objects are created. If you are concerned about performance it may be a better idea to create a specialized overload that takes the array and extra parameters).

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

Comments

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.