dotnet / dotnet/linker

Getting to the Subclass of a MemberExpression using Type is not trim compatible

Open
#3,105 13 comments 0 reactions 0 assignees View on GitHub
area-Linker: DataFlow
Dominant language
C#
Stars
392
Forks
128
Avg merge
2d 10h
Merged PRs (30d)
2

Description

Consider the following code with an inherited model that I want to retrieve an attribute from.
The result should be "Bar". Note the attribute we want to get is on derived class.

Just accessing `memberExpression.Member` won't work as that returns the base class (as per the IL)
I have to use `Type` property to get to the derived class.

However

```cs
memberExpression.Expression?.Type.GetProperty(memberExpression.Member.Name);
```
gives me a trim warning I cant seem to resolve.

```
(local variable) PropertyInfo property
'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperty(String)'. The return value of method 'System.Linq.Expressions.Expression.Type.get' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to. \[MudBlazor\]csharp(IL2075)
```

Is there anyway I can make this trim compatible 🙏 .
Our library uses the Type property in a few places and we want to support trimming and reading attributes from subclassed models.

Sample code (not tested)

```cs
class TestFailingModel
{
[Label("Foo")]
public virtual string Foo { get; set; }
}

class TestFailingModel2 : TestFailingModel
{
[Label("Bar")]
public override string Foo { get; set; }
}
```

```cs
var model = new TestFailingModel2();
Expression expression = () => model.Foo;
Console.WriteLine(expression.GetLabelString());
```
```
Output should be "Bar"
```

```cs
public static string GetLabelString(this Expression> expression)
{
var memberExpression = (MemberExpression)expression.Body;
var propertyInfo = memberExpression.Expression?.Type.GetProperty(memberExpression.Member.Name);
return propertyInfo?.GetCustomAttributes(typeof(LabelAttribute), true).Cast().FirstOrDefault()?.Name ?? string.Empty;
}
```

Reference
https://github.com/MudBlazor/MudBlazor/issues/5586
https://stackoverflow.com/questions/74315845/get-propertyinfo-for-a-subclass-from-expression-in-a-trim-friendly-way?noredirect=1&lq=1

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.