Recently I decompiled some code and the behaviour of the compiled code differed from the original program.
So I think there might be a bug somewhere.
In a simple program I tried to reproduce the problem.
The decompiled code looked something like this:

static void Main(string[] args)
{
Predicate<DataClass> p = null;
List<DataClass> l = new List<DataClass>();

l.Add(new DataClass("key1", "value1"));
l.Add(new DataClass("key2", "value2"));
l.Add(new DataClass("key3", "value3"));
l.Add(new DataClass("key4", "value4"));

for (int i = 1; i <= 4; i++)
{
string s = "key" + i.ToString();
if (p == null)
{
p = delegate(DataClass dc)
{
return dc.Key==s;
};
}
Console.WriteLine(l.Find(p).Value);
}
}

This code shows four times value1.
It should show four different values.
The problem van be solved in two different ways:

1) Remove the check if (p==null)
The following code works correct:

static void Main(string[] args)
{
Predicate<DataClass> p = null;
List<DataClass> l = new List<DataClass>();

l.Add(new DataClass("key1", "value1"));
l.Add(new DataClass("key2", "value2"));
l.Add(new DataClass("key3", "value3"));
l.Add(new DataClass("key4", "value4"));

for (int i = 1; i <= 4; i++)
{
string s = "key" + i.ToString();
p = delegate(DataClass dc)
{
return dc.Key==s;
};
Console.WriteLine(l.Find(p).Value);
}
}


2) Declare s on the same level as p:
The following code also works correct:

static void Main(string[] args)
{
Predicate<DataClass> p = null;
List<DataClass> l = new List<DataClass>();

l.Add(new DataClass("key1", "value1"));
l.Add(new DataClass("key2", "value2"));
l.Add(new DataClass("key3", "value3"));
l.Add(new DataClass("key4", "value4"));

string s;

for (int i = 1; i <= 4; i++)
{
s = "key" + i.ToString();
if (p == null)
{
p = delegate(DataClass dc)
{
return dc.Key==s;
};
}
Console.WriteLine(l.Find(p).Value);
}
}
hromkes
0

Comments

4 comments

  • Clive Tong
    Hi.

    Do you have an example of some C# which gives a bad decompilation?

    If not could you send me the IL (from the IL view in Reflector) of the method which decompiles incorrectly?

    Thanks

    [clive DOT tong AT redgate DOT com]
    Clive Tong
    0
  • Clive Tong
    Thanks for the various examples you sent through to me. I logged the bug as RP-709.

    There was a problem with one of the optimisations that was moving the declaration of a closed over variable to make it part of the assignment of the variable. This is now fixed.
    Clive Tong
    0
  • hromkes
    When is the new version available for download?
    hromkes
    0
  • Clive Tong
    We should be releasing an EAP (early access) version of the next release within a couple of weeks.
    Clive Tong
    0

Add comment

Please sign in to leave a comment.