开发者

Is get Property called on construction or only when the Property is called?

开发者 https://www.devze.com 2022-12-13 22:13 出处:网络
I have a piece of code that I would like to set as part of the get {} section of a property. However, inside this section I call a SQL query.

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

I would like to know if the call will be made when the object is constructed (i.e.开发者_开发知识库 Object t = new Object()) or only when the property is called (i.e. string query = Object.SqlQuery).


The code is only run when the property is called. It's easy to verify this 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


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

The exception to this is if you are calling the getter of the property from within the constructor of the class.


The sql statement will only be executed when the property is accessed, this is known as lazy loading. Use something like sql profiler if you want proof.


The getter of the property is called when you read from it, like so:

var yourVar = this.yourProperty;

The setter is called when you assign the property, like so:

this.yourProperty = yourVar;

Does this help?

0

精彩评论

暂无评论...
验证码 换一张
取 消