wasatz
wasatz

Reputation: 4278

Is it possible to specify an Expression for a single property selector?

I can specify that a method takes an Expression<Func<Foo, object>> as an argument in order to get an api that looks something like this:

// With a method declaration like this...
public void Foo(Expression<Func<Bar, object>> selector) { .... }

// ...I can invoke the method like this
Foo(b => b.Baz);
Foo(b => new { b.Baz, b.Foo });

However, I am writing an API which would benefit from being able to only allow a single property to be chosen. Like this:

public void Foo(Expression<Func<Bar, ...>> selector) { .... }

// This would be OK.
Foo(b => b.Baz);

// But this would not...
Foo(b => new { b.Baz, b.Foo });

Is there a way to express this to restrict the expressions in this way?

Of course, I could always just document this and check the expressions during runtime, but if possible I would prefer to make an API that doesn't throw RuntimeExceptions if I can avoid it.

Edit:

I guess I could change the return value of the Func in the method declaration to be a specific type and thus restrict the expressions a bit at least. But I'd prefer not to do this since I'd like to be able to accept pretty much any type of property in this method call.

Upvotes: 0

Views: 162

Answers (2)

David
David

Reputation: 10708

If you use a specific parent object for acceptable types, the following would enforce parameters at compile-time

public void Foo<TSource, TTarget>(Expression<Func<TSource, TTarget>> selector)
    where TSource : Bar
    where TTarget : Bar
{ ... }

Since anonymous types derives from object, this will prevent their use, since both TSource and TTarget must derive from Bar

However, this only specifies that the source and result are derived from a specific type - checking what the expression is is, by definition, a runtime check, since you're validating data in an object.

Upvotes: 0

Servy
Servy

Reputation: 203835

No, there is no way to require, through static checking, that the expression is only a property access of the property of the expression. You can only ever perform such a check at runtime.

Upvotes: 2

Related Questions