ManInMoon ManInMoon - 1 month ago 4x
C# Question

Is there a simpler way to return fields from static function?

I often want to parse a string into various bits and have a readable way to return them.

I like this approach, but it involves creating a specific class

long orderID = Utils.UnTradeIdent(tradeIdent).OrderID;

In Utils.cs:

public class TradeIdentData
public string AccountIdent;
public long OrderID;
public string SubID;

public static TradeIdentData UnTradeIdent(string tradeIdent)
TradeIdentData tradeIdentData = new TradeIdentData();

var parts = tradeIdent.Split('!');
tradeIdentData.AccountIdent = parts[0];
if (parts[1].Contains("."))
var bits = parts[1].Split('.');
tradeIdentData.OrderID = long.Parse(bits[1]);
tradeIdentData.SubID = bits[1];
tradeIdentData.OrderID = long.Parse(parts[1]);
tradeIdentData.SubID = "";

return tradeIdentData;



A separate class with well-named properties (which you are already using) is currently the most readable way of doing this.

In C# 7 you will be able to use tuples for return values, like so:

public static (string AccountIdent, string OrderID, string SubID) UnTradeIdent(string tradeIdent)
    string accountIdent, orderID, subID ;

    ... Code to initialise accountIdent, orderID and subID appropriately ...

    // Now return the data as a tuple:       

    return (accountIdent, orderID, subID);

You can consume this as follows:

long orderID = Utils.UnTradeIdent(tradeIdent).OrderID;

Or if you want all the values:

var result = Utils.UnTradeIdent(tradeIdent);
// Use result.OrderId, result.SubID or result.AccountIdent

This is not going to be available until some time next year, though.

Also, even though this new tuple support makes it more convenient to WRITE the code, it doesn't let you document it using XML comments as well. Spending the time to write a simple and well-documented class will still often be better than using the new C# 7 tuple support.

See here for more details.