I am using an expression to identify a specific method in a class, and return the attribute of the method. When the method is async, the compiler gives me a warning that the method should be awaited.
Are there any other ways I could identify the method, or any way to suppress the warning, without using pragma? I would like not to use a string to identify the method.
Resharper suggests async/await, but async lambda expression cannot be converted to expression trees.
Other answers are extension methods for task, but then I would not be able to get the method with the attribute.
Example code:
class Program
{
static void Main(string[] args)
{
var attributeProvider = new AttributeProvider();
var attributeText = attributeProvider.GetAttribute<Program>(
p => p.MethodA()); //Warning: Because this call is not awaited, ...
}
[Text("text")]
public async Task<string> MethodA()
{
return await Task.FromResult("");
}
}
public class AttributeProvider
{
public string GetAttribute<T>(Expression<Action<T>> method)
{
var expr =(MethodCallExpression) method.Body;
var attribute = (TextAttribute)Attribute.GetCustomAttribute(
expr.Method, typeof(TextAttribute));
return attribute.Text;
}
}
public class TextAttribute : Attribute
{
public string Text { get; set; }
public TextAttribute(string text)
{
Text = text;
}
}
Since it's just an Action<T>
, the compiler sees that you are invoking a Task but not doing anything with it. In this case, that's deliberate so you could ignore the warning. To avoid the warning, you could add an overload of the GetAttribute method to take an Func<T,object>
instead of an Action<T>
.
public string GetAttribute<T1>(Expression<Func<T1,object>> method)
This way, the compiler will see that you are expecting a result (in this case a Task) and will assume you will do something with it and not warn you about not awaiting it.
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