Using temporary variables?

Reply Forum
Forum postRobert @ 2011-09-11 16:34:46
ReplyReply to
Hi. I'm really new to C# (and programming in general).

I want a variable to only exist for the duration of a Method and then when the Methods done be removed from memory. Is there a way of declaring a variable like this or removing it from memory manually and how is this done?

I tried searching but I just kept finding stuff about the temporary folder which I think is different...

Thank you very much for any response. :)
Rob


Forum postgrechzoo @ 2011-09-27 17:48:54
ReplyReply to
variables created within methods will be deleted once the block has been exited.

static public void Main()
{
//call method
method();
}

public method()
{
int num = 10;

for(int i = 0; i < num; i++)
Console.WriteLine(num);
}

this method is called from main. create an integer within the method and is used in a loop which basically counts from 0-9 in a command prompt window.

as soon as this method has finished. the block is exited and any variable created within that block is automatically deleted. so num is deleted (as is i). no extra commands are needed.

C# has garbage collection. you dont really need to worry about manually deleting any variable or class.












© net-tutorials.com 2006 - 2012

MailContact net-tutorials.com