Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using Lazy.Value right after its declaration

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?

like image 944
Adassko Avatar asked Sep 20 '13 12:09

Adassko


1 Answers

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".

like image 56
Ogre Psalm33 Avatar answered Sep 24 '22 14:09

Ogre Psalm33