Question

I have this method

public Sorting(Expression<Func<T, object>> property, bool ascending = true)

and I want to be able to call it something like this

public Sorting(null)

By this I mean I want to specify no expression and use the default value for ascending.

How do I do this?

Était-ce utile?

La solution

If you do not need to specify expression, then create overload for this constructor (I think its constructor, not simple method) which don't have expression parameter (instead of passing null):

public Sorting(Expression<Func<T, object>> property, bool ascending = true)
public Sorting(bool ascending = true)

Side note - I also don't like passing boolean values to methods, because they are not expressive and its hard to understand what they mean:

Sorting(false) // what is that?

Usually I create different methods instead (like OrderBy and OrderByDescending) or pass some enumeration (like Order.Ascending and Order.Descending). With constructors you cannot specify custom name, so I use static creation methods for that. That is much easier to read:

Sorting.CreateDescendingSorting()
Sorting(Order.Ascending)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top