user6269870
user6269870

Reputation:

Return an object along with a list

In a method

  1. count is calculated

  2. 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

Answers (4)

Hamid Pourjam
Hamid Pourjam

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; }
}

FxCop rule for out parametes.

Upvotes: 2

Raghuveer
Raghuveer

Reputation: 2637

2 options

  1. using out param for count, with return type as List
  2. using a Tuple or custom Class which will contain both of your 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

Hari Prasad
Hari Prasad

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

monstertjie_za
monstertjie_za

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

Related Questions