Reputation: 19619
static void Main(string[] args)
{
foo f1 = new foo();
string s1 = f1.fooMethod();
string s2 = (new foo()).fooMethod();
// Does anonymous object destroys here?
// some more code....
//....
//....
//....
//....
// f1 is accessible here also
// some more code....
//....
//....
//....
//....
// f1 is accessible here also
}
class foo
{
public string fooMethod()
{
return "fooMethod called";
}
}
in above code I have created an anonymous object using (new foo())
syntax (I suppose this is what these objects are called) and one f1
object.
Now f1
is accessible in whole code block but that anonymous object is not (of course).
The questions are:
f1
object creation (specially when we
need to call just one method of that class like in this case)?Upvotes: 4
Views: 119
Reputation: 7036
When you use word 'accessible' in your comment, actually you mean variable scope. When you use word 'destroy', actually you mean garbage collection. They are totally different things. One is C# syntax, the other is CLR runtime behavior.
To answer you specific question:
Upvotes: 0
Reputation: 12626
I suppose this is what these objects are called
I'm not so sure about that. MSDN does not recognize anonymous objects. It's simply an object that you don't keep a reference to longer than you need. However, CLR keeps the reference until a garbage collection takes place.
Does that anonymous object destroys in next line as soon as it's work is done?
Not necessarily.
Is this way of creating anonymous objects is good or bad in comparison to the f1 object creation
No, it's fine. I'll explain basics of GC in the next few lines.
So how is it with memory reclaiming in .NET?
When you allocate a memory for a resource (an object for instance), it will be stored in the generation 0 on the managed heap. When this generation is full of objects, GC runs
All objects with a flag 1 are moved to the next generation and the rest of the currently checked generation is reclaimed. This means, that both of your objects can live exactly the same time under some circumstances.
This is by no means a complete description of .NET GC, just an introduction. If you are instereted in more details, read some article or a book.
Upvotes: 3