Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple or Object array is best to return from a method for multiple values in C#?

Tags:

c#

.net

My current code is

object[] method()
{
returning new object[] {"",12,} like this ?
}

Is Tuple a better option instead ?

I got some information about Tuple performance here

Please suggest a good option to move..

This class is used frequently and request will be frequent.

UPDATE

That return values is differs in different methods. I have all methods return's values from 2 to 10 as max.

Logic is i m converting sp [MS SQL stored procedure] logic to mongoDb equivalent ( all data are present )

So for sp one method is there which should return as sp returns.In sp for that OUT parameters is used and it returns some integer values also.

In replacing that i m using

object[] method(out int returnValue)
 {
 }

returnValue is for error code and object[] as return type for sp's out parameters.

What is best way to do this ?

like image 474
shanmugharaj Avatar asked Oct 25 '13 06:10

shanmugharaj


People also ask

Can tuple return multiple values?

F# Return Multiple Values Using Tuples Function does not return multiple values.

What is the best way to return multiple values from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

Can you return multiple values in C?

We know that the syntax of functions in C doesn't allow us to return multiple values. But programmers often need to return multiple values from a function.


2 Answers

You also have a 3rd option: a simple typed result class or struct with properties. Tuple is okay if you are returning not more then 3 items.

Returning an object array in C# is a bad practice - try to be as typed as possible. As a general rule of thumb you are creating the code for your fellow developer (so that he/she can use/modify it easily) and not the computer. Let optimizations happen by the framework.

like image 172
Peter Aron Zentai Avatar answered Sep 19 '22 18:09

Peter Aron Zentai


I would just create a new class and return instances of it instead. That gives you a type safety and readability thanks to proper property names instead of Item1, Item2.

Instead of array return IEnumerable<> - that way you can change the implementation of the method (for instance by introducing yield return) without breaking consumers.

And remember that

premature optimisation is the root of all evil

like image 36
Jakub Konecki Avatar answered Sep 17 '22 18:09

Jakub Konecki