3 ms·
The author is complaining about explicit use of 'this' where it's not required. It's hardly incorrect, it's a preference. I'd personally pick explicit use of th
by caseymarquis 6y ago
The author is complaining about explicit use of 'this' where it's not required. It's hardly incorrect, it's a preference. I'd personally pick explicit use of this if I cared enough be consistent about it. I've specifically been bitten by refactoring a local variable to the same name as a private variable on accident, and shadowing the private variable within the local scope. Using explicit this prevents that from happening.
Now, if you want an example of incorrect C#, I'm sure I can find something I've got running in production much worse than explicit this...
Posting from mobile, so formatting might have issues, but below I'm monkey patching a bug out of the immutable AST Entity Framework generates when using SQL Server's DateDiff function. On the one hand it's truly monstrous. On the other hand, it's saved hundreds of lines of code elsewhere in the application.
public static IQueryable<IGrouping<TKey, TSource>> GroupByDateDiff<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) {
var body = (NewExpression)keySelector.Body;
foreach (var arg in body.Arguments) {
if (arg.NodeType == ExpressionType.Call) {
var callNode = (MethodCallExpression)arg;
if (callNode.Method.Name == "DateDiff") {
var dateDiffFirstArg = callNode.Arguments[0];
if (dateDiffFirstArg.NodeType == ExpressionType.Constant) {
//It was already a constant, so we're good.
}
else {
//HACK: This will break if the internal implementation of ReadOnlyCollection changes.
var listInfo = typeof(ReadOnlyCollection<Expression>).GetField("list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var list = (IList)listInfo.GetValue(callNode.Arguments);
if (dateDiffFirstArg.NodeType == ExpressionType.MemberAccess) {
list[0] = Expression.Constant((string)GetMemberValue((MemberExpression)dateDiffFirstArg));
}
else {
throw new ArgumentException($"{nameof(GroupByDateDiff)} was unable to parse the datePartArg argument to the DateDiff function.");
}
}
}
}
}
return source.GroupBy(keySelector);
}