Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable in static methods inside static class

please consider this code :

1)public static class MyClass
2){
3)    public static DateTime MyMethod(DateTime dt)
4)    {
5)         DateTime temp = new DateTime();
6)         temp = dt.AddDays(1);
7)         return temp;
8)    }
9)}

Does temp variable has instance per any calls to MyMethod? or because it is in a static method inside static class just one instance of temp variable allocate in memory?

thanks

like image 890
Arian Avatar asked Feb 10 '26 13:02

Arian


2 Answers

temp is neither a static nor an instance variable, it is a local variable. It absolutely does not matter whether the method in which it is declared is static or not: the variable's scope starts at the point of its declaration, and ends at the closing curly brace } of the scope in which it is declared. Each executing thread that goes through MyMethod gets its own copy of temp, which is invisible anywhere outside the variable's scope.

like image 194
Sergey Kalinichenko Avatar answered Feb 13 '26 08:02

Sergey Kalinichenko


Does temp variable has instance per any calls to MyMethod?

If you mean "does each call to MyMethod get a separate temp variable?" then the answer is yes.

The fact that it's a static method in a static class is irrelevant - it's a local variable, so you get a "new" local variable on each call.

like image 37
Jon Skeet Avatar answered Feb 13 '26 09:02

Jon Skeet