1

I have a common method which accepts array of object as parameter.

Now, there are instances where I need to pass just a single object to function call. To save lines of code and memory, I try doing it inline as:

func(new ObjectType(param));

But this doesn't compile as it is expecting an array of object. How can I transform this object into an array inside my function call? (Does it require another constructor or operator overloading?)

1
  • 1
    new Object[] { object_i_want_in_array }? Or something like that? Or make an override of the function to take just one? Commented Dec 1, 2014 at 13:38

2 Answers 2

4

I assume the function signature is func(object[] items)?

Few options:

  • create a new array: func(new[] { new ObjectType(param) })

  • add a new overload that takes a single parameter: func(object item)

  • change the signature to params: func(params object[] items). This would take an array or an zero of more objects (e.g. func(item1, item2, item3))

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

5 Comments

For the first option, I have overridden the default constructor. So I suppose it won't work. 3rd option seems good
I'm not sure what the constructor has to do with it. You may have to post some more code to clarify what func is and where it's declared.
There's nothing wrong on having multiple constructor signatures on c#
@Jcl its not wrong but i suppose it would require me to define a default construct explicitly as well. which I do not want to.
@Saksham I don't understand what you mean. If you have Class(object a) and Class(object[] a) you can do new Class with either signature. Inside Class you can do constructor chaining if you need it.
0

Make use of the params keyword:

private void MyFunc(params string[] args)
{
    foreach(string s in args)
    {
        Console.WriteLine(s);
    }
}

Test it like this

MyFunc("foo"); // pass single string
MyFunc(new string[] {"foo", "bar"}); // pass array

To be honest, the compiler generates code which creates a new array with a single element if you pass a single string. This shouldn't be a problem, except the function is very performance-critical.

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.