.net - Should C# have a lazy key word -
should c# have lazy keyword make lazy initialization easier?
e.g.
public lazy string lazyinitializestring = getstringfromdatabase();
instead of
private string _backingfield; public string lazyinitializestring { { if (_backingfield == null) _backingfield = getstringfromdatabase(); return _backingfield; } }
i don't know keyword has system.lazy<t>
type.
- it officially part of .net framework 4.0.
- it allows lazy loading of value
member
. - it supports
lambda expression
ormethod
provide value.
example:
public class classwithlazymember { lazy<string> lazysource; public string lazyvalue { { if (lazysource == null) { lazysource = new lazy<string>(getstringfromdatabase); // same lazysource = new lazy<string>(() => "hello, lazy world!"); // or lazysource = new lazy<string>(() => getstringfromdatabase()); } return lazysource.value; } } public string getstringfromdatabase() { return "hello, lazy world!"; } }
test:
var obj = new classwithlazymember(); messagebox.show(obj.lazyvalue); // calls getstringfromdatabase() messagebox.show(obj.lazyvalue); // not call getstringfromdatabase()
in above test code, getstringfromdatabase()
gets called once. think want.
edit:
after having comments @dthorpe , @joe, can following shortest can be:
public class classwithlazymember { lazy<string> lazysource; public string lazyvalue { { return lazysource.value; } } public classwithlazymember() { lazysource = new lazy<string>(getstringfromdatabase); } public string getstringfromdatabase() { return "hello, lazy world!"; } }
because following not compile:
public lazy<string> lazyinitializestring = new lazy<string>(() => { return getstringfromdatabase(); });
and property type of lazy<string>
not string
. you need access it's value using lazyinitializestring.value
.
and, open suggestions on how make shorter.
Comments
Post a Comment