Reputation: 5343
There's a lot of code like this in company's application I'm working at:
var something = new Lazy<ISomething>(() =>
(ISomething)SomethingFactory
.GetSomething<ISomething>(args));
ISomething sth = something.Value;
From my understanding of Lazy
this is totally meaningless, but I'm new at the company and I don't want to argue without reason.
So - does this code have any sense?
Upvotes: 6
Views: 215
Reputation: 21946
Code that is being actively developed is never static, so one possibility of why they code it this way is in case they need to move the assignment to another place in the code later on. However, it sounds as if this is occurring within a method, and normally I would expect Lazy initialization to occur most often for class fields or properties, where it would make more sense (because you may not know which method in the class would first use it).
Unfortunately, it could just as likely be more a lack of knowledge of how the Lazy feature works in C# (or lazy init in general), and maybe they are just trying to use the latest "cool feature" they found out about.
I have seen weird or odd things proliferate in code at a company, simply because people saw it coded one way, and then just copied it, because they thought the original person knew what they were doing and it made sense. The best thing to do is to ask why it was done that way. Worst case, you'll learn something about your company's procedures or coding practices. Best case, you may wind up educating them if they say "gee, I don't know".
Upvotes: 4
Reputation: 2240
It can be useful if the Lazy.Value
is going to be moved out of the method in the future, but anyway it can be considered as overengineering, and not the best implementation as the Lazy
declaration seemed to be extracted to a property in this case.
Thus shortly - yes, it's useless.
Upvotes: 1
Reputation: 877
Unless they are using something
multiple times in the method, it seems pretty useless, and slightly less efficient than just performing the action immediately. Otherwise, Lazy<T>
is going through the Value
get
and checking to see if the value has been materialized yet, and performing a Func
call.. Usefull for deferred loading, but pointless if it is just used once in a method immediately..
Lazy<T>
however is usually really helpful for Properties on a class
Upvotes: 1
Reputation: 21855
Well, in this case is meaningless of course because you are getting the value right after creating the object but maybe this is done to follow a standard or something like that.
At my company we do similar things registering the objects in the Unity container and calling Unity to create the instance just after registering it.
Upvotes: 1