how can I return more than one type in c# function like I want to return string and datatable ?
5 Answers
The simplest answer is to use the DataTable's TableName
property.
The more general answer is to use a Tuple<DataTable, string>
or write a class or struct.

- 868,454
- 176
- 1,908
- 1,964
-
is this only in .Net 4 ? because I try it but VS2008 didn't know waht is tuple :S – kartal Dec 03 '10 at 03:33
-
@salamo: The `Tuple` class is new to .Net 4.0. The `TableName` property isn't. – SLaks Dec 03 '10 at 03:36
use ref or out parameters
ref parameter : requires initilization by the caller method.
public string ReturnName(ref int position)
{
position = 1;
return "Temp"
}
public string GetName()
{
int i =0;
string name = ReturnName(ref i);
// you will get name as Temp and i =1
}
// best use out parameter is the TryGetXXX patternn in various places like (int.TryParse,DateTime.TryParse)
int i ;
bool isValid = int.TryParse("123s",out i);

- 17,262
- 5
- 38
- 63
Use an out parameter:
public string Function(out DataTable result)
Call it like this:
DataTable table;
string result = Function(out table);

- 43,592
- 5
- 83
- 98
You can define your own class to use as the return type:
class MyReturnType
{
public string String { get; set; }
public DataTable Table { get; set; }
}
and return an instance of that. You could use a Tuple but it's often better to have meaningful type and property names, especially if someone else is going to be working on the software.
Or you could use an out
parameter on the function.
The way you go depends on what is suitable for your situation. If the string and the DataTable are two parts of the same thing a class makes sense. If the string is for an error message when creating the DataTable fails an out parameter might be more appropriate.

- 13,947
- 3
- 24
- 33