2

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

Arian
  • 12,793
  • 66
  • 176
  • 300

4 Answers4

7

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • thanks dear friend.you mean if I place `SqlConnection` inside that method and open and close it that connection would open and close within each thread and every thread does not affect connection for other thread? – Arian Jun 21 '12 at 20:48
  • @Kerezo Yes, that is absolutely correct: each executing thread gets its own variable, no matter how many threads get at it concurrently. – Sergey Kalinichenko Jun 21 '12 at 20:55
4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • you said `The fact that it's a static method in a static class is irrelevant` but in extension methods we do this – Arian Jun 21 '12 at 20:15
  • 2
    @Kerezo: What do you mean by "we do this"? Even in extension methods, local variables are still local variables... – Jon Skeet Jun 21 '12 at 20:21
0

temp has one instance per call.

BTW I'm missing possibility to define static local variables in static methods as in C++.

brgerner
  • 4,287
  • 4
  • 23
  • 38
0

The temp variable, even in a static method, has to be declared a static, otherwise it is just created locally in that instance, then blown away when the method call ends.

Bob.
  • 3,894
  • 4
  • 44
  • 76