开发者

return more than one output on c#

开发者 https://www.devze.com 2023-01-28 07:47 出处:网络
how c开发者_如何学Can I return more than one type in c# function like I want to return string and datatable ?The simplest answer is to use the DataTable\'s TableName property.

how c开发者_如何学Can I return more than one type in c# function like I want to return string and datatable ?


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.


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


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.


Use an out parameter:

public string Function(out DataTable result)

Call it like this:

DataTable table;
string result = Function(out table);


use a tuple as a return.

0

精彩评论

暂无评论...
验证码 换一张
取 消