Home > Enterprise >  Initializing a variable and passing it as a parameter vs initializing in method body [closed]
Initializing a variable and passing it as a parameter vs initializing in method body [closed]

Time:09-25

In C#, does anyone know if doing this...

 public object Foo()
 {
    var command = new MyCommand(param1);
    return Myfunction(command);
 }

is less efficient (uses more memory) than doing this?

 public object Foo()
 {
    return Myfunction(new MyCommand(param1));
 }

Or is the difference only cosmetic? It seems like the first option would consume a little more memory until the variable falls out of scope. I realize any difference would be very small. Also, is there name for 2nd syntax? inline? something? Thanks!

CodePudding user response:

To the compiler, it is exactly the same. Both will get converted to the same IL code.

Two things to keep in mind.

First, how readable is your code? With a single variable it looks fine, but what happens if you are passing in multiple variables or doing nested function calls like return Myfunction(new MyCommand(MyOtherFunction(MyThirdFunction(param1))));? Technically, this is correct but it makes it much harder to read and understand.

Second, how easy it is to debug? What happens if your command is null. Do you need to check it and if yes, where? Based on param1, you may not know the value of the command until further in your code so if something goes wrong, it may be much harder to find where.

 public object Foo()
 {
    var command = new MyCommand(param1); // what happens if param1 is invalid?
    
    if (command != null) // yes, this can be done on one line
    {
        return MyFunction(command);
    }
    else
    {
        throw new ArgumentException("Bad command"), ex);
    }
 }

CodePudding user response:

There is no difference. The compiler will optimize the command variable away.

  • Related