By default, parameters are passed by value. That means that any changes made to the value of the parameters within the method will not be visible to the calling method.
Passing Parameters - C# Programming Guide | Microsoft Docs[
^]
Parameter passing in C#[
^]
If you want the changes to be visible to the calling method, then you need to pass the parameters by reference. You do this by using either the
ref
or
out
modifiers.
ref keyword - C# Reference | Microsoft Docs[
^]
out parameter modifier - C# Reference | Microsoft Docs[
^]
For example:
public ActionResult Index()
{
const string barcodeTopParent = "DT-COMPSTART";
const string barcodeMiddleParent = "DB-TEST";
const string barcodeBottomParent = "SP-SLD";
string strTopBarCode, strMiddleBarCode, strBottomBarCode;
helper.ReadBarcodeFromFile(file.FullName, out strTopBarCode, out strMiddleBarCode, out strBottomBarCode);
if (strTopBarCode == barcodeTopParent || strMiddleBarCode == barcodeMiddleParent || strBottomBarCode == barcodeBottomParent)
{
...
}
}
public void ReadBarcodeFromFile(string _Filepath, out string strTopBarCode, out string strMiddleBarCode, out string strBottomBarCode)
{
string[] barcodes = BarcodeScanner.Scan(_Filepath, BarcodeType.Code39);
if (barcodes.Length != 0)
{
strTopBarCode = barcodes[0];
strMiddleBarCode = barcodes[1];
strBottomBarCode = barcodes[2];
}
else
{
strTopBarCode = null;
strMiddleBarCode = null;
strBottomBarCode = null;
}
}
NB: There are some cases where you are not allowed to pass by reference - particularly
async
methods and iterator methods.
Passing by reference is also often considered a "code smell", and should be avoided wherever possible. You could either create a specific type to hold multiple return values, or return a
ValueTuple
instead.
Tuple types - C# Guide | Microsoft Docs[
^]
public ActionResult Index()
{
const string barcodeTopParent = "DT-COMPSTART";
const string barcodeMiddleParent = "DB-TEST";
const string barcodeBottomParent = "SP-SLD";
var barcodes = helper.ReadBarcodeFromFile(file.FullName);
if (barcodes.topBarCode == barcodeTopParent || barcodes.middleBarCode == barcodeMiddleParent || barcodes.bottomBarCode == barcodeBottomParent)
{
...
}
}
public (string topBarCode, string middleBarCode, string bottomBarCode) ReadBarcodeFromFile(string _Filepath)
{
string[] barcodes = BarcodeScanner.Scan(_Filepath, BarcodeType.Code39);
if (barcodes.Length != 0) return (barcodes[0], barcodes[1], barcodes[2]);
return default;
}