Variables with Mian and scope?

I have this code…

    
  void ProgramStarted()
        {       
Devices = new zDevice[20];///declared outside ProgramStarted, hence doesn't get out of scope issue.

            // Digital Outputs 17-32
            zDevice relay01 = new zDevice() { DeviceId = 20, TypeId = 1 /*Digitaloutputs*/, DeviveName = "relay01", description = " ", DefaultValue = false, Value = 0, Position = Pin.GP0B };
            Devices[0] = relay01;
            zDevice relay02 = new zDevice() { DeviceId = 21, TypeId = 1 /*Digitaloutputs*/, DeviveName = "relay02", description = " ", DefaultValue = false, Value = 0, Position = Pin.GP1B };
            Devices[1] = relay02;
}

I am accessing zDevice array within a timer constantly, my question is whether the assigned object like relay01 will loose its reference? ie if i access Devices[1] will it become null?

@ anthonys - No, when you assigned the relays to a position within the device array their reference count increased to two. When you left ProgramStarted their reference count was reduced by one. Since their reference count was greater than zero, because of the reference within the device array they are not GC’s.

Does NETMF use a reference counting GC?

(Totally an aside, does not affect Mike’s answer in any way)

Absolutely… how else could you do proper GC?

@ Mike - Fuzzy logic AI-based GC.

You could do it the way the desktop .NET does it, with a generational mark-and-sweep GC. This type of GC is known as a “tracing garbage collector”, and it’s the most common type, more common than simple reference counting. This type has the advantage that circular references don’t result in memory leaks.

1 Like

Absolutely not. NETMF uses a simple mark-and-sweep GC (there are other approaches, like generational garbage collection). Unlike reference counting, true GC algorithms can also deal with cyclic data structures automatically.

2 Likes