Skip to content

Commit af653cc

Browse files
committed
parser: invoke static delegate members accessed through a type
Invoking a static member of a delegate type through the name of its type, such as 'Formulas.Square(2)' for a registered type with a static Func<int, int> Square, failed with "Cannot access a member on a null reference", because the code expected the member to always have an instance. Access the member without an instance, since a member bound through a type is static.
1 parent d83b6cd commit af653cc

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

‎src/Ramstack.ExpressionParser/ExpressionBuilder.cs‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -301,12 +301,8 @@ Expression ProcessMemberAccess(Expr.MemberAccess e)
301301
Error.NonInvocableMember(m);
302302

303303
//
304-
// This shouldn't happen, but we'll crash if it does
304+
// A member accessed through a type is static, so it is accessed without an instance.
305305
//
306-
if (expression is null)
307-
throw new InvalidOperationException(
308-
"Cannot access a member on a null reference.");
309-
310306
expression = Expression.MakeMemberAccess(expression, memberInfo);
311307
return Invoke(expression, null);
312308
}

‎tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,20 @@ public void Evaluate_ElementsForParamArray_CreatesArray(string expression, objec
169169
public void Evaluate_DelegateMember_CallsDelegateAndItsMethods(string expression, object expected) =>
170170
Assert.That(ExpressionParser.Evaluate(expression, new DelegateContext()), Is.EqualTo(expected));
171171

172+
[TestCase("StaticDelegates.Tripler(2)")]
173+
[TestCase("StaticDelegates.Tripler.Invoke(2)")]
174+
public void Evaluate_StaticDelegateMemberOfType_CallsDelegate(string expression)
175+
{
176+
var binder = new DefaultBinder();
177+
binder.RegisterType(typeof(StaticDelegates));
178+
179+
var result = ExpressionParser.Parse(expression, binder);
180+
Assert.That(result.Success, Is.True, result.ErrorMessage);
181+
182+
var value = Expression.Lambda<Func<int>>(result.Value!).Compile()();
183+
Assert.That(value, Is.EqualTo(6));
184+
}
185+
172186
[TestCase("Defaults()", "1 Monday True null")]
173187
[TestCase("""Defaults(5, DayOfWeek.Friday, Guid.NewGuid(), "a")""", "5 Friday False a")]
174188
[TestCase("Mixed(1)", "1 2 0")]
@@ -502,6 +516,11 @@ public class DelegateContext
502516
public Func<int, int> Doubler { get; } = x => x * 2;
503517
}
504518

519+
public static class StaticDelegates
520+
{
521+
public static Func<int, int> Tripler { get; } = x => x * 3;
522+
}
523+
505524
public class OptionalContext
506525
{
507526
public static string Defaults(int number = 1, DayOfWeek? day = DayOfWeek.Monday, Guid id = default, string? text = null) =>

0 commit comments

Comments
 (0)