1

In C# when you have a property:

public class Person
{
  public int AnIntegerValue
  {
    get
    {
      //Some logic
      return somevalue;
    }

  }
}

When you go and get a Person from the database:

 var mike = Uow.GetPerson("Mike");

is the AnIntegerValue evaluated immediately or does the code wait for:

mike.AnIntegerValue

I'm wondering because this would obviously affect performance if you were to put a lot of logic into the property and it was eager loaded.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
user2005657
  • 607
  • 10
  • 20

3 Answers3

3

Properties are not being evaluated immediately. They are evaluated upon accessing the "get" modifier.

Explanation:

At the bottom line, there is no real difference between a function and a property.
Meaning:

public int AnIntegerValue
  {
    get
    {
      //Some logic
      return somevalue;
    }

  }

Is equivalent to:

Public int get_AnIntegerValue()
  {

      //Some logic
      return somevalue;  

  }

And in fact, this is exactly what your properties are compiled to (you can see that if you follow the stack while debugging).

So, In the same manner that functions are not being evaluated immediately, same goes for properties, and you can use them without worrying about extra cost performance wise.

You can take a look at this thread for some guidelines about when to use properties and when functions will be the better and elegant way to go.

Community
  • 1
  • 1
Avi Turner
  • 10,234
  • 7
  • 48
  • 75
1

It depends on the implementation of GetPerson(). By default when instantiating a class its properties are not evaluated (the getters won't be run). The backing variables for the properties will be initialised to the default value for their type.

Monstieur
  • 7,992
  • 10
  • 51
  • 77
0

You should be loading your entire object (or aggregate, as it is called in domain-driven design). Lazy-loading is a technique used with related objects. My opinion is that one should not use lazy-loading as it is a sympton of querying one's object graph.

Quite a lot of detail one can go into so I'll stick with the short answer: do not lazy properties/columns and attempt to never lazy-load :)

Eben Roux
  • 12,983
  • 2
  • 27
  • 48