Home > Back-end >  Object as a parameter without declaring a variable
Object as a parameter without declaring a variable

Time:10-11

Why is it possible to create a new object and use it as a parameter WITHOUT declaring "pathVariable"?

ExcelPkg.SaveAs(new FileInfo(@"D:\New.xlsx"))

Otherwise, code below causes an error. Why?

package.SaveAs(FileInfo pathVariable = new FileInfo(@"D:\New.xlsx"))

CodePudding user response:

The first question you have to ask yourself is: "What is a variable anyway?" Technically a variable is just something that stores the address/position in the heap/stack/memory of an Object that has been created. It's useful becasue you can re-use that same in-memory object multiple times by always saying to the computer "hey i need that exact thingie i used before right here".

But it's not necessary to re-use it, is it? If you just need some data value for that brief micro-/nano-/milisecond, you don't have to remember where you put it.

Think of it as having plates. You can just use paper or any other kind of one-time-use plates for your breakfast meal, or you use the multiple use plates you keep at home in a cupboard of some sort (probably). So when you want to use your favourite plate for breakfast, you have to know where to get it. Did you leave it in the sink? Was it cleaned and put in the cupboard? Did you leave it at your desk? (A "variable" answers that question in your stead, virtually of course).

So why doesn't this work?:

package.SaveAs(FileInfo pathVariable = new FileInfo(@"D:\New.xlsx"))

bacasue it's a C# syntax error to declare and set a variable in a function parameter. A variable declaration has no place inside a function call. Well technically, nor does a variable definition. And your example is both of those.

Why does this work?

ExcelPkg.SaveAs(new FileInfo(@"D:\New.xlsx"))

Because it's the same as setting a variable, using it and then throwing it away, like so:

FileInfo someTemporaryVariableNameyouDontEvenHaveToRemember = new FileInfo(@"D:\New.xlsx");
ExcelPkg.SaveAs(someTemporaryVariableNameyouDontEvenHaveToRemember);
//Oh, i don't need it anymore
someTemporaryVariableNameyouDontEvenHaveToRemember=null;

CodePudding user response:

You can assign and use it as argument if declare somewhere outside:

FileInfo pathVariable;
package.SaveAs(pathVariable = new FileInfo(@"D:\New.xlsx"))

also as multiple:

private void MyMethod()
{ 
    string arg1;
    int arg2;
    bool arg3;

    MyMethod(arg1 = "SomeString", arg2 = 123, arg3 = true);
}

private void MyOtherMethod(string arg1, int arg2, bool arg3)
{ 
    // arg1 will be "SomeString"
    // arg2 will be 123
    // arg1 will be true

    string newArg;

    MyVeryOtherMethod(newArg = arg1.Substring(0, 7)); // "SomeStr"
}

private void MyVeryOtherMethod(string arg)
{ 
    // arg will be "SomeStr"
}

I don't saying it is good practice and proper usage. It is possible and only.

  • Related