As several people have indicated in the comments, the indiscriminate use of out
and ref
is a bad practice.
With that said, your first major problem is that the code as written doesn’t compile because you’re passing parameters in in the wrong order. For example:
CalculateCostMeth(ref numberOfDrawers, ref cost, ref deskWoodType);
should actually be
CalculateCostMeth(ref deskWoodType, ref numberOfDrawers, ref cost);
Even then it won’t compile because “cost” is a) the wrong type and b) should be passed with “out” instead of “ref.”
Same thing for OutPutCostMeth
– the order’s completely scrambled.
OutPutCostMeth(ref deskWoodType, cost, numberOfDrawers);
It should actually be
OutPutCostMeth(numberOfDrawers, ref deskWoodType, cost);
Also, “deskWoodType” shouldn’t include the “ref” keyword.
Also, “cost” is a double in the main method and an int in the “OutPutCostMeth” – you can’t implicitly convert a double to an int because that may entail data loss. Here are the correct signatures:
// New signature - change int cost to double cost and change the return type
private static double CalculateCostMeth(ref string deskWoodType, ref int numberOfDrawers, out double cost)
// Change cost to a double
private static void OutPutCostMeth(int numberOfDrawers, string deskWoodType, double cost)
Here are the correct calls:
CalculateCostMeth(ref deskWoodType, ref numberOfDrawers, out cost);
OutPutCostMeth(numberOfDrawers, deskWoodType, cost);
One final point: make sure you validate user input. Right now entering some random string will make the program crash. I also claimed that I wanted -20 drawers and the program informed me that the store owes me $500. I’d strongly suggest making sure you handle obviously invalid input like that gracefully.
1
solved C# Methods in console Based [closed]