Virtual properties and lazy loading

By definition, virtual properties or methods are methods that are visible to overridden subclasses. But, for example, NHibernate uses virtual properties to provide lazy loading.

My question is not about NHibernate, but how can you use virtual properties to achieve lazy loading? Are there any hidden behaviors regarding virtual properties that I don't know?

+6
source share
2 answers

The fact that they are declared virtual allows NHibernate to redefine a property and create a proxy implementation for it, in turn, they can use it to implement lazy loading on first access to the property.

+9
source

There is no hidden behavior behind virtual . Except for the not-so-hidden fact that they can be overridden in child classes.

False loading can be achieved using the Lazy<T> class. In which T is the type to be loaded. It will implicitly convert to T

Or if you want to manually adjust the properties to behave lazily, you can use something like this:

 private SomeType _someProperty = null; public override SomeType SomeProperty { get { if (_someProperty == null) { // Load _someProperty } return _someProperty; } } 

With ValueTypes you can make them Nullable<T> . Or enter bool whether they are loaded or not.

+2
source

Source: https://habr.com/ru/post/905774/


All Articles