Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time error wanted for List<>.Sort() with no sort specification

Tags:

c#

.net

Is there some way of defining a class such that if I mistakenly attempt to sort a List<> of the objects with no sort specifications it will generate a compile-time error?

So when I correctly specify, for example

listOfMyObjects.Sort(MyObject.CompareFieldNames);

it will be accepted, but if I forget and specify

listOfMyObjects.Sort();

then I'll get a compile-time error.

(I do realize that I'll get a runtime-error - but what I'd prefer is some way of getting a compile-time error.)

EDIT:

Just to make it very clear, I want to get a compile-time error for the second example above.

The situation, which I find myself in occasionally, is that I have a class with several different Comparison<> methods. Let's say it can be sorted by FieldName or it can be sorted by DateOfCreation. Now, what I want to avoid is accidently/mistakenly thinking, "oh yes, good old object X, it's sortable by date of creation, so I'll just sort this list with Sort() and go merrily on my way ...", but in fact the default sorting method is sort by FieldName (so the sorting is wrong) or there is no default sorting method (so I get a runtime error).

So I want to force myself (or anyone else working with my object) to remember that there are several ways to sort the object, and one of the methods should be explicitly chosen.

like image 965
RenniePet Avatar asked Nov 30 '12 11:11

RenniePet


3 Answers

You could write a custom FxCop rule, see here for a tutorial.

Have a look at this tutorial for Code Analysis.

like image 125
Patrick McDonald Avatar answered Nov 11 '22 06:11

Patrick McDonald


You can do it by sub-classing and then with the ObsoleteAttribute - not ideal, but you'll get an error:

public class MyList<T> : List<T>
{
  public MyList() {}
  public MyList(int capacity) : base(capacity) {}
  public MyList(IEnumerable<T> range) : base(range) {}

  [Obsolete("Please do not use this method", true)]
  public new void Sort(){ throw new NotSupportedException(); }
}

public void Test() 
{
  var l = new MyList<string>();
  l.Sort(); //<--- compile-time error
}

Only works, however, if the compile-time type of l is MyList<T>, because you're just defining a new Sort method that replaces the base version - but it's not virtual.

like image 2
Andras Zoltan Avatar answered Nov 11 '22 05:11

Andras Zoltan


Forcing compile time error is not possible. You can set rules like Obsolete but that are just workaround.

like image 1
Tilak Avatar answered Nov 11 '22 06:11

Tilak