Reputation:
In a method
count is calculated
a list is also formed
I need to return this count along with the list in c#. Any suggestions on how to return this?
Upvotes: 1
Views: 430
Reputation: 20764
You should avoid using out and ref parameters.
I suggest creating a type that represents the output result.
public DoSomethingResult DoSomething()
{
var result = new DoSomethingResult();
//....
result.Data = GenerateList();
result.Count = CalculateCount();
return result;
}
public class DoSomethingResult
{
public List<YourType> Data { get; set; }
public int Count { get; set; }
}
Upvotes: 2
Reputation: 2637
2 options
Count
and List
Sample Code:
public List<Class1> GetData(out int Count)
{
//...
//Your Logic with returning list
}
Option2:
public CustomClass DoSomething()
{
var data = new CustomClass();
//....
data.Data = list;
data.Count = list.Count();
return data;
}
public class CustomClass
{
public List<Class1> Data { get; set; }
public int Count { get; set; }
}
Upvotes: 0
Reputation: 16966
You could simply return a List
and a get a Count
in caller method. You don't really require to return both.
Still interested? multiple options.
Using out
parameter for count.
public List<something> DoSomething(out int count)
{
....
count = list.Count();
return list;
}
using Tuple
as pointed in comments.
public Tuple<List<something>, int> DoSomething()
{
....
return new Tuple<List<something>, int>(list1, count);
}
Upvotes: 0
Reputation: 7823
You should use the out keyword in C#.
MSDN description. "Declaring an out method is useful when you want a method to return multiple values. This enables methods to return values optionally."
Here is the MSDN documentation.
Here is an example:
public List<YourType> SomeMethodName(out int count)
{
//Your calculation here
}
Upvotes: 0