I want to return multiple parameter from a method in c#.I just wanted to know which one is better out or Tuple?
static void Split (string name, out string firstNames, out string lastName)
{
int i = name.LastIndexOf (' ');
firstNames = name.Substring (0, i);
lastName = name.Substring (i + 1);
}
static Tuple<string,string> Split (string name)
{
//TODO
}
There is usually a (value) class hiding somewhere if you need to return more than one value from a method. How about a value class with the Split()
method as ctor:
public class Name
{
public Name(string name)
{
int i = name.LastIndexOf (' ');
FirstNames = name.Substring (0, i);
LastName = name.Substring (i + 1);
}
public string FirstName {get; private set;}
public string LastName {get; private set;}
}
Instead of
Split(name, out string firstName, out string lastName);
just do
Name n = new Name(name);
and access the first and last name via n.FirstName
and n.LastName
.
Though this is a necro I would like to add that, given the new features in C#9 and C#10, the tuple approach is more intuitive and takes advantage of anonymous types. Sometimes classes are just overkill - especially if this function is an extension method.
You can now use this signature syntax for tuples:
public (T1, T2, T3, .... TN) MyMethod(your parameters)
And also pre-name tuple entries: (Using your example)
static (string firstName, string LastName) Split (string name)
{
int i = name.LastIndexOf (' ');
return (name.Substring (0, i), name.Substring (i + 1));
}
If you'd like, you can also fill the result tuple data into existing variables:
string name = "Cat Dog";
string firstName, lastName;
(firstName, lastName) = Split(name);
/// firstName = Cat, lastName = Dog
Either of these implementations is very readable, maintainable, and modular - since you don't need to define a class.
My personal preference is that you should only define a class if there is an internal object state or necessary methods needed for the data - otherwise use a tuple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With