global vs local

  • Thread starter Thread starter JJ
  • Start date Start date
J

JJ

Hi All,

I was wondering if I create an object in public main
does it persist for the lifetime of the app? If not where
do u create objects that will persist for the lifetime of
app so that when I call a method in a class I can
reference that object? By the way I am creating a win
form app in c#.

Thanks,

JJ
 
Managed apps (ie, garbage collected) take some adjustments in thinking. You
can create a "local" object and pass a reference to it to another variable
(variable B), and even when the original reference goes out of scope, the
object will remain accessible thru variable B. Therefore, it will not go out
of scope nor be garbage collected as long as there remains any valid
reference to it anywhere in your app. Reference objects are all created on
the managed heap.

Mountain
 
JJ,

This depends. If it is a local variable, then it might not. If the
variable is not passed to anything and not referenced further in the
procedure, then the CLR might determine that it is not accessible and make
it eligible for garbage collection.

However, this is digressing. For what you want to do, you probably want
to expose whatever value/property/object you want using a static property.
You can make a static property/field and that will last for the lifetime of
the application.

Hope this helps.
 
Thanks Guys,

I think I understand. So if I create, let's say a
XPathNavigator object to a XmlPathDocument and I want to
reference it in another procedure. One I can put it in
the method signature a (XPathNavigator nav1) and ref that
way or two I can create a static XpathNavigator varaible,
XPathNavigator nav2 in class global and then assign it in
the initial procedure such as
XPathNavigator nav = xd.CreateNavigator();
nav2 = nav;

Correct?

If so what is the proper coding way of doing things
meaning which method is preferable?

Thanks,
JJ
 
Back
Top