GigiF
GigiF

Reputation: 83

Method arguments in C# possible like this?

I have an assignment from my teacher and I think that the task in not possible but he insists that it can be done: basically I need to create o method WriteSum that adds two integer numbers and the method is called by him in the main method while I must write the WriteSum method code in a class: He insists that the method must be called like this: WriteSum(22+24) with return value 46. Is this possible??? From what I know in C# method arguments are given with commas between them so his correct code for calling the method should be WriteSum(22,24)???

His code is like this:

string n = Calculator.WriteSum(22+24);
Console.WriteLine(n);
Console.Read();

And I have to write the "WriteSum" method in a class Calculator.

Upvotes: 4

Views: 134

Answers (1)

Heinzi
Heinzi

Reputation: 172220

You are right: C# will evaluate the expression 22+24 before calling your method. In other words, WriteSum(22+24) will behave exactly like WriteSum(46), i.e., it will

  1. call a single-parameter method with the name WriteSum and
  2. pass the integer expression 46 as the argument.

Thus, the requirements as stated in your question cannot be fulfilled. As others have mentioned in the comments, it is possible that your instructor actually meant to assign you one of the following tasks:

  1. Just write the value of the parameter that has been passed. In that case, however, the method should be called WriteInt instead of WriteSum and the implementation would be trivial.
  2. If the method takes a string argument (i.e. WriteSum("22+24")), you'd need to parse the string, extract the summands, add them, and print (or return) the result. This does sound like a realistic task given to a student.

In any case, you should really clarify the requirements before you start to implement anything.

Upvotes: 5

Related Questions