c# - does final static automatically employ lazy instantiation? -


the page @ http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=5 says code this:

public final static singleton instance = new singleton(); 

automatically employs lazy instantiation.

i want verify if

1) compilers this, or compiler free whatever wishes to

2) , since c# not have "final" keyword, what's best way translate c# (and @ same time should automatically employ lazy instantiation too)

yes. static initializer guaranteed run before able access instance. there 2 negatives approach:

  1. if error occurs within singleton's construction, error little harder debug ("error in initializer").
  2. on first use of class, object instantiated. if did locking approach, not instantiated until needed. however, being example singleton, not problem at all, drag on unused, yet lazily instantiated piece of code elsewhere not singleton.

the translation c# readonly instead of final.

in opinion, still vastly preferable secondary approach (synchronized/locked, checked instantiation within static getter) because not require synchronization code, faster, easier read , easy use.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -