6

Is there an easy way to refactor a field/property of type T to be a Lazy, and replace all useages of that field to use FieldName.Value instead?

I have a controller with a bunch of dependencies that are stored in private backing fields, but only a few of the dependencies are need on any given function call. In order to speed up construction of this controller, I'd like to make all the dependencies Lazy, but its just an irritating amount of work to do by hand. Any advice?

hermitt
  • 515
  • 4
  • 8
  • 2
    I think the easiest is if it's a field, refactor to a property. then, in the getter, change the backing field to a `Lazy` and return it's `Value` property in that getter. i.e. there isn't a specific refactoring for this. – Peter Ritchie Apr 27 '14 at 18:46

2 Answers2

4
  1. Tools > Create GUID

  2. Resharper > Refactor > Rename

    Foo => Foo_299E4ADB-5770-458C-B030-E40E19B0FFAF

  3. Edit > Find and Replace > Replace in Files

    _299E4ADB-5770-458C-B030-E40E19B0FFAF => .Value

Ilya Kozhevnikov
  • 10,242
  • 4
  • 40
  • 70
2

if previously you had,

public class LazyClass
{
 // initialized in constructor etc.
 public MyType MyTypeProperty { get; set; }
}

then you can make it lazy loaded, without affecting the callers as follows:

public class LazyClass
{
 private Lazy<MyType> myType = new Lazy<MyType>(() => new MyType());

 public MyType MyTypeProperty
 {
  get { return this.myType.Value; }
 }
}

i doubt if Resharper has this re-factoring built in. anyways, you don't want all callers to know it is Lazy and refer to it as LazyType.Value. don't expose the Lazy type.

Raja Nadar
  • 9,409
  • 2
  • 32
  • 41
  • To clarify, the fields i would be changing are private to the class, so I think its fine to have them pure Lazy's and not wrapped by a property accessor. If I were to have external properties, I would absolutely use this method. – hermitt Apr 27 '14 at 21:52