FOR NEX issue

This forum is meant for questions and discussions about the X# language and tools
Post Reply
boonnam
Posts: 88
Joined: Mon May 08, 2017 6:42 pm
Location: USA

FOR NEX issue

Post by boonnam »

m_dibs is private variable:

C#
private System.IntPtr[] m_dibs;

or

X#
private m_dibs as IntPtr[]

In the constructor for the class:

m_dibs = new System.IntPtr[0];

or

m_dibs := IntPtr[]{0}

Here is my C# sample code:

Code: Select all

//int x = m_dibs.Length;

for (int i = 0; i < m_dibs.Length; i++)
{
      EZTwain.DIB_Free(m_dibs[i]);
}
Here is my X# translation:

Code: Select all

x := self:m_dibs.Length
            
for i := 0 upto self:m_dibs.Length
     EZTwain.DIB_Free(self:m_dibs[i])
next
In the C#, since the length is 0 when the class is first instantiated, the code inside the for next loop doesn't run. But in the X#, the line inside the for next loop get executed, which resulted in index out of range error. I also use "to" instead of "upto".

I know I can prevent this by first checking if the length is > 0 before running the for next loop or perhaps initialize i := 1.

I am using Core dialect. "Use Zero Base Arrays" is false at first. I also tried setting to true. Same result.

Is there a similar code for X#?. I thought the index in Core dialect is zero base like C#.


Thanks,
Boonnam
User avatar
Chris
Posts: 4562
Joined: Thu Oct 08, 2015 7:48 am
Location: Greece

FOR NEX issue

Post by Chris »

Hi Boonam,

Are you using zero-based arrays in X#? If yes, then your iteration should be upto length - 1:

Code: Select all

for i := 0 upto self:m_dibs.Length - 1
If you think about it, it's the same tha c# does, with the "i < m_dibs.Length" segment in the for command. It uses "<", not "<=", so "i" never reaches "m_dibs.Length".

With the above correction, the loop will not execute at all also in X# for an empty array.

If you're not using zero-based arrays, then (unlike in c# which does not support 1-based array indexing) you'd need to start the loop from element "1":

Code: Select all

for i := 1 upto self:m_dibs.Length
In both cases, the result will now be the expected one.

Chris
Chris Pyrgas

XSharp Development Team test
chris(at)xsharp.eu
boonnam
Posts: 88
Joined: Mon May 08, 2017 6:42 pm
Location: USA

FOR NEX issue

Post by boonnam »

Thank you very much!
Post Reply