RenniePet
RenniePet

Reputation: 11658

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

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.

Upvotes: 5

Views: 212

Answers (3)

Patrick McDonald
Patrick McDonald

Reputation: 65451

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

Have a look at this tutorial for Code Analysis.

Upvotes: 4

Tilak
Tilak

Reputation: 30728

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

Upvotes: 1

Andras Zoltan
Andras Zoltan

Reputation: 42363

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.

Upvotes: 2

Related Questions