• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 572
  • Last Modified:

c# local variable lazy initialization

can someone tell me the pros and cons of lazy initializing local variables?  my main concern about using this technique is that there is always the possibility that a variable doesn't get lazy initialized because it's being used in a whole bunch of places.  so as opposed to writing lazy initialization code in multiple places possibly, why not just initialize it the moment you declare it.
0
mmingfeilam
Asked:
mmingfeilam
1 Solution
 
käµfm³d 👽Commented:
I'll have to defer for the "cons", but regarding this statement: " so as opposed to writing lazy initialization code in multiple places possibly"...

I would say that if you are duplicating your "lazy initialization" code in multiple places, then you are probably doing something wrong. Lazy initialization just means that you don't instantiate something until you need it. For local variables, I would wonder under what circumstances you were contemplating lazy initialization. If you have a lengthy function, then it may be the case that your function requires refactoring anyway. If you have a normal function, then any expensive-to-create objects which you have declared locally I would expect to have been coded in such a manner that you really wouldn't need lazy initialization--but I'm rather sleepy, so I'm sure I could be overlooking something.

From what I am reading, lazy initialization is akin to the Singleton pattern. I would inquire as to whether or not a pattern like that would suit your environment.
0
 
mmingfeilamAuthor Commented:
what i mean by lazy init is this:

MyClass var = null;

...
if(condition1)
  var = new MyClass();
else if(condition2)
...
else if(condition3)
  var = new MyClass();
else
 ...
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now