Bastien Vandamme
Bastien Vandamme

Reputation: 18465

Using variable assignment vs repeating method

I would like to know. What is the most performant or correct way to write code between repeating a method or using a unique assignment an assignment

 // Solution 1
 if (!string.IsNullOrEmpty(Files[m].Trim()))
 {
     Attachment oAttch = new Attachment(Files[m].Trim());
     Msg.Attachments.Add(oAttch);
     Log.LogAttachment(Files[m].Trim());
 }

 // Solution 2
 string file = Files[m].Trim();
 if (!string.IsNullOrEmpty(file))
 {
     Attachment oAttch = new Attachment(file);
     Msg.Attachments.Add(oAttch);
     Log.LogAttachment(file);
 }

I prefer solution 2 and I thing this is the correct way to write code. But I would like to know if I'm missing something, something I don't know about the compiler, about C#.

Upvotes: 2

Views: 115

Answers (1)

Ian
Ian

Reputation: 30813

The single assignment is mostly preferred if the value does not change along the way, that is, your solution 2. This is because repeating the method will increase the time overhead to call and re-call the method for the same result. The second benefit for this use is likely a smaller amount of code since you do not write .Method() multiple times.

But if a method produces different results every time it is called, like Random.Next(), then you have to repeat the method calling.

So the key here is really to know if a method re-calling produces any difference.

Upvotes: 2

Related Questions