Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# avoiding variable declaration

Tags:

c#

Suppose I have some code like this:

public string SomeMethod(int Parameter)
{
  string TheString = "";

  TheString = SomeOtherMethod(Parameter);

  return TheString;
}

Of course, this code is equivalent to this:

public string SomeMethod(int Parameter)
{
  return SomeOtherMethod(Parameter);
}

I think the first version is more readable and that's how I'm writing my code, even thought I'm using a variable when I know I could avoid it. My question is this: does the compiler compile the code in the same way (ie same performance) or is the second option really better in terms of performance.

Thanks.

like image 976
frenchie Avatar asked Apr 07 '12 12:04

frenchie


2 Answers

I'd say the first form is less readable and it contains a redundant initializer. Why initialize the variable to "" if you're about to give it a different value? At least change it to:

public string SomeMethod(int parameter)
{
  string returnValue = SomeOtherMethod(parameter);    
  return returnValue;
}

or if you really want to separate declaration from initialization:

public string SomeMethod(int parameter)
{
  string returnValue;
  returnValue = SomeOtherMethod(parameter);    
  return returnValue;
}

(Note that I've also adjusted the named to follow .NET naming conventions and to give a more meaningful name to the local variable -"TheString" conveys no useful meaning.)

You really won't see any performance problems from using the local variable, but I'd really encourage you to think about the readability. What is the purpose of the local variable here? You'd presumably describe the method as: "Returns the result of calling SomeOtherMethod with the given parameter" - at which point, the one-line version implements exactly that description.

like image 155
Jon Skeet Avatar answered Oct 27 '22 14:10

Jon Skeet


The compiler will produce very similar code for your two examples. One slight modification though is to avoid initializing to an empty string that you never use.

public string SomeMethod(int Parameter)
{
    string result;
    result = SomeOtherMethod(Parameter);
    return result;
}

I'm not sure rewriting the code in this way makes it more readable, but it does mean that you can add a breakpoint and see the value of result before the method returns. This can be useful when debugging.

Note you can combine the first and second line and still get this benefit:

public string SomeMethod(int Parameter)
{
    string result = SomeOtherMethod(Parameter);
    return result;
}

I think this last version is both highly readable and easy to debug.

like image 39
Mark Byers Avatar answered Oct 27 '22 12:10

Mark Byers