Instantiated variable does not contain any value

149 views Asked by At

I have a class called ClassModel. This is how it looks.

class ClassModel
{
    dynamic ConnListInstance;

    public ClassModel() {
        ConnListInstance = Activator.CreateInstance(Type.GetTypeFromProgID("PCOMM.autECLConnlist"));
    }

    public void checkCount() { //this shows a count of 0
        Console.WriteLine(ConnListInstance.Count());
    }

    public void checkCountVersionTwo() { //this shows a count of 1
        ConnListInstance = Activator.CreateInstance(Type.GetTypeFromProgID("PCOMM.autECLConnlist"));
        Console.WriteLine(ConnListInstance.Count());
    }
}

I have instantiated the class in my main page by declaring ClassModel obj = new ClassModel().

But when I try calling the checkCount method, it returns 0 instead of 1. The checkCountVersionTwo returns 1 but only because I have added the instantiation from the constructor.

Is there something wrong with the way I have created my constructor and class? May I know why it is returning a null/empty value? Shouldn't the variable ConnListInstance have a value upon creating a new ClassModel object?

2

There are 2 answers

1
dymanoid On BEST ANSWER

This has nothing to do with your code, but the reason is in the way how this object works.

Please read the documentation:

An autECLConnList object provides a static snapshot of current connections. The list is not dynamically updated as connections are started and stopped. The Refresh method is automatically called upon construction of the autECLConnList object. If you use the autECLConnList object right after its construction, your list of connections is current. However, you should call the Refresh method in the autECLConnList object before accessing its other methods if some time has passed since its construction to ensure that you have current data. Once you have called Refresh you may begin walking through the collection

(emphasis mine)

So the solution is:

public void checkCount() 
{
    ConnListInstance.Refresh();
    Console.WriteLine(ConnListInstance.Count());
}
0
NitinSingh On

Is this the complete code without any other manipulation anywhere?

Ad per this, following seem the case. Please add further code to clarify.

  1. In constructor, you will have a valid instance, unless the CreateInstance fails for some reason

  2. In 1st check method, you will get the count of whatever entity it holds (from construction time to method call time).

  3. In 2nd check method, you are recreating the object and again retrieving its count in same block. So any possible time for entity's to be added to list is within the constructor of ConnListInstance.

Hence, for #2, it seems that you are manipulating the underlying data being contained and hence the list count is reported as 0; whereas at time of fresh construction, it's reported as 1.