Error: An expression tree may not contain a reference to a local function
public void Initialize()
{
CloudStorageProperties ImageFileProperties(string fileName) => _cloudStorage.GetBlob(CloudStorageType.Image, fileName).FileProperties;
Config = new MapperConfiguration(x =>
{
x.CreateMap<Category, CategoryViewModel>()
.ForMember(vm => vm.ImagePath, m => m.MapFrom(src => ImageFileProperties(src.ImageFile.Name).Uri.AbsoluteUri));
});
}
I can replace the local function with an anonymous function and it works but re sharper says that I should convert it to a local function.
Why is this not allowed?
Here is the pull request in Roslyn which makes this change:
References to local functions are now disallowed in expression trees, which may or may not change in the future (Previously they were generated as a reference to a mangled method name, which seemed wrong). Added a new error for this.
So the reasoning behind this is: when you reference a method in expression tree - it is represented as MethodCall
expression with given method name. If you reference local function with name ImageFileProperties
- you would expect MethodCall
with the same name. Expression tree purpose is to be analyzed and deconstructed, so names are important there. But in reality local functions are compiled as static function with names like <Initialize>g__ImageFileProperties1_0
(what is referenced to as "mangled method name" in quotation above). For this reason Roslyn developer(s) decided to just not allow this to avoid confusion (name of the function you see in source code and name of the function in expression tree). With anonymous function there is no such confusion, so they are allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With