0

I have a function in class A:

public int RecordSummary()
        {
            int result = 0;
            int recordsAffected = 0;

            SqlCommand cmd = new SqlCommand("spIATRecordSummary", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            var returnParameter = cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
            returnParameter.Direction = ParameterDirection.ReturnValue;

            try
            {
                conn.Open();
                recordsAffected = cmd.ExecuteNonQuery();
                result = Convert.ToInt32(returnParameter.Value);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
            -- I want to return these two: 
            return result;
            return recordsAffected;
        }

I want to get 2 values from this function and return it to two different variables.

From the other class how would I go about populating two variables?

Class B:

int RESULT = RecordSummary();
int RECORDS_AFFECTED = RecordSummary();

I've been reading on tuples and using the out parameter but I'm not sure how the caller will actually retrieve the data. Any help?

Quuxplusone
  • 23,928
  • 8
  • 94
  • 159
JJ.
  • 9,580
  • 37
  • 116
  • 189
  • Out parameters can be harder to understand so the Microsoft recommendation for class library design is to avoid out parameters: http://msdn.microsoft.com/en-us/library/ms229053(v=vs.100) – Martin Liversage Sep 03 '12 at 06:22

1 Answers1

1

Here's how you could use an out parameter:

int GetRecordSummary(out int recordsAffected)
{
    // If necessary - basically this variable *must* be definitely
    // assigned by the time you return; your code currently just
    // catches exceptions thrown by the block that would assign
    // a value :(
    recordsAffected = -1;
    ...
    // Code as before
    ...
    return result;
}

Then call it with:

int recordsAffected;
int result = GetRecordSummary(out recordsAffected);

See the MSDN documentation on out for more details.

Alternatives:

  • Create your own type to encapsulate the two values, and return a value of that type
  • Return a Tuple<int, int> if you're using .NET 4 or higher:

    ... in the method ...
    return Tuple.Of(result, recordsAffected);
    
    ... in the caller ...
    var results = GetRecordSummary();
    int result = results.Item1;
    int recordsAffected = results.Item2;
    
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194