calynr
calynr

Reputation: 1282

When is the variable created?

I would like to know when I have specified below the variable "temp" is created ?

public class tempClass
{
    public string prop_temp
    {
        get
        {
            string temp = "temp";
            return temp;//When  is the variable created ?
        }
    }  
}

static void Main()
{
    tempClass x = new tempClass(); //Is the variable created now?;
    string b = x.prop_temp;//Or now ?
}

Upvotes: 1

Views: 74

Answers (3)

Kyle W
Kyle W

Reputation: 3752

I think you're confusing the variable with the item that it points to. The variable is either just a code construct, or a pointer, depending on how you look at it. The variables in your code are "temp", "b", and "x". The variable "temp" will get optimized out by the compiler, and never exist. What I think you're asking is when does the object represented by "temp" get created. That object is in the compiled code, and exists as the code is running. This is specifically because it is a string, and strings are immutable. If the object had been a class, it would indeed get created (the object, not the variable) when you called the method.

Upvotes: 0

PelinErgenekon
PelinErgenekon

Reputation: 21

Of course

string b = x.prop_temp;//Or now ?

Is where your variable temp is created. Check where you declared the variable, it's in prop_temp property. So it will be created when you call prop_temp.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

In this case, the variable is created when you access the property, not when you create the class.

A property getter is really "shorthand" for a method. As such, your temp variable is just like any other local variable within a method, and doesn't exist until the method is run.

Upvotes: 4

Related Questions