Is the get property called by the construct, or only when the property is called?

I have a piece of code that I would like to set as part of the get {} section of the property. However, inside this section I am invoking an SQL query.

I would like to know if the call will be executed when the object is built (i.e. Object t = new Object ()) or only when the property is called (i.e. string query = Object.SqlQuery).

+3
source share
4 answers

Code runs only when a property is called. This is easy to check for yourself:

class MyClass
{
    public string SqlQuery
    {
        get
        {
            Console.WriteLine("Code was run here!");
            return "foo";
        }
    }    
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Constructing object.");
        MyClass myObject = new MyClass();
        Console.WriteLine("Getting property.");
        string sqlQuery = myObject.SqlQuery;
        Console.WriteLine("Got property: " + sqlQuery);
    }
}

Output:

Constructing object.
Getting property.
Code was run here!
Got property: foo
+2
source

The code inside the get section of your property will only be called when the getter property is called. It will not be called when a new object is created.

, getter .

0

The sql statement will be executed only when accessing the resource, this is called lazy loading . Use something like a sql profiler if you want to get proof.

0
source

The property receiver is called when you read it, for example:

var yourVar = this.yourProperty;

The setter is called when the property is assigned as follows:

this.yourProperty = yourVar;

Does it help?

0
source

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


All Articles