Consider the GetPropertyName method in the code sample below:
using System;
using System.Linq.Expressions;
namespace SampleApp
{
public class Program
{
public static void Main()
{
var name = GetPropertyName<Box, string>(b => b.Position);
Console.WriteLine(name);
}
private static string GetPropertyName<T, TP>(Expression<Func<T, TP>> exp)
{
var memberExpression = exp.Body as MemberExpression;
return memberExpression == null ? null : memberExpression.Member.Name;
}
}
public class Box
{
public string Position { get; set; }
}
}
Is there any way of making that method's parameter so specific that it wouldn't compile unless a get+set property is being passed? Something like this:
private static string GetPropertyName<T, TP>(PropertyExpression<T, TP>> exp) {}
... to fix situations like this at compile time:
var name = GetPropertyName<Box, string>(b => "AAA");
PS: will Roslyn fix this situation?
PPS: context: implementing a strict internal DSL.
Is there any way of making that method's parameter so specific that it wouldn't compile unless a get+set property is being passed?
No. It's just a lambda expression. There are restrictions about what kind of lambda expressions can be converted into expression trees, but nothing that says it's just got to be a property.
PS: will Roslyn fix this situation?
Well, you could add a code diagnostic to check this... but better, you could use nameof
in C# 6 to avoid having a GetPropertyName
method at all.
See more on this question at Stackoverflow