In C# you have a number of options available when you need to return more than one value from a method call.
- Return a complex object containing multiple properties such as a Class or a Struct
- Return OUT parameters
- Return Ref parameters
- Return a tuple
If you already have a Class or Struct defined in your business objects this is an excellent way to go.
When your requirements are more dynamic, and a business object has not already been defined for frequent use, the last three options work nicely.
The Out and Ref parameters are defined in a method input parameters, and then specified as Out or Ref when calling the method. The difference is that with a Ref parameter, you need to initialize it before calling the method, and the method does not have to modify the object sent as a Ref parameter. With an Out parameter, you do not have to initialize the object before the method call. However, the method must set a value for the Out parameter before returning.
The Tuple is a more recent technique utilizing generics. You can define a tuple with any number of data attributes, each having its own unique type definition.
For example, tuple<int, string, double> myTuple
defines a complex variable myTuple
with three properties. The first property is an int
, second a string
, and the third a double
. This is like creating a class dynamically without naming the properties. The properties are therefore referenced by their ordinal position as myTuple.Item1
, etc.
Using a tuple you can create a method returning a complex object that is defined as you define the method, returning the tuple value.
That’s my C# method output review for the year.
Cheers,
Ben