Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'base' keyword in delegate causes System.BadImageFormatException

Tags:

c#-4.0

I have a weird problem and I would like if someone can enlighten me on why is this happening. I have a protected method in a base abstract class as following:

protected T ForExistingEntity<T>(TEntity entity, object key, Func<Entity, T> action) {
    entity = GetByKey(key);
    if (entity != null)
        return action(entity);

    return default(T); 
}

My original call from an inherited class was as follows:

return base.ForExistingEntity(
    new MyEntity(), key, e => {
        e.someFiled = 5;
        return base.Update(e);
    }
);

When this code executes, an exception get raised at the line that reads:

return action(entity);

in the base abstract class. The exception is:

System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Now when I modify my call as following:

return base.ForExistingEntity(
    new MyEntity(), key, e => {
        e.someFiled = 5;
        return Update(e);
    }
);

it runs normally without any issues.

Edit:

The Update method is located in the base abstract class and looks like this:

public virtual bool Update(TEntity entity) {
    Condition.Requires(entity, "entity")
        .IsNotNull();

    if (ValidateEntity(entity))
        return Update(entity, true);

    return false;
}

I am starting to think that this is happening because of Update being virtual and the call actually originates in the base class itself? The exception isn't very helpfull anyway.

like image 593
Alaa Avatar asked Mar 13 '11 16:03

Alaa


1 Answers

This seems to be a known C# compiler bug involving calling a base virtual method from an anonymous method within a generic class. Don't hesitate to upvote this bug on connect if you want it solved. Fortunately, the workaround is quite simple here.

like image 131
Julien Lebosquain Avatar answered Oct 22 '22 19:10

Julien Lebosquain