tags:

views:

29

answers:

4

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).

A: 

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.

adrianbanks
A: 

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.

Paul Creasey
A: 

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?

Maximilian Mayerl
⁢s⁢/⁢z⁢/⁢y⁢/⁢g⁢
Mark Byers
Sorry? What do you mena by that comment?
Maximilian Mayerl
It means you typed z instead of y multiple times. You already fixed it now so it's OK. :)
Mark Byers
+2  A: 

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
Mark Byers
Thanks for the example as well! That's what made it click for me!
WedTM
An example is worth a thousand words. :)
Mark Byers