2

The C# spec probably says so, but even though nothing showed up in my search, that's not the answer I'm looking for.

I'm looking for scenarios that show that calling operator methods (like op_Addition) or property accessors (like get_Length) directly might be a bad idea. Bad enough for the designers of the C# language to stop us from doing it. (See compiler error CS0571.)

One fairly common scenario where it would be useful to have this ability is where a Func<T> delegate should return the value of a property. You can't make the get accessor the method of the delegate, either. There's a simple work-around (use () => someObject.SomeProperty), but, even aside from the overhead, it's not as clear as someObject.get_SomeProperty.

The one complication I see is that, when a type defines multiple conversions to different types, the methods would have the same signature with different return types, which C# doesn't allow either. But that's a different question.

Community
  • 1
  • 1
Jeffrey Sax
  • 10,253
  • 3
  • 29
  • 40
  • 2
    See for instance this answer. Every feature has a cost. http://stackoverflow.com/a/4914207/161457 – TrueWill Jan 11 '12 at 03:32
  • @TrueWill Generating a unique compile-time error to disallow it is a feature, too. So then, why was the cost of allowing considered greater than the cost of disallowing? – Jeffrey Sax Jan 11 '12 at 03:48
  • `() => someObject.SomeProperty` is not the same as `someObject.get_SomeProperty`. The first is an anonymous function that returns a property. The second is the property gettor function itself (and, when used in an expression without parentheses, one would expect it to return a delegate to the function). – Abel Mar 04 '12 at 21:17

1 Answers1

1

Not sure why the designer (Anders) chose not to support it, but here are some good reasons I came up with.

  1. It would be confusing to beginners who do not know that the default name for a property getter is get_PropertyName (but it doesn't have to be if it's a standard compiler assembly).

  2. You would probably have some java-ophiles that would never use the convention.

  3. If the class designer wanted to (and it makes sense), you can have an Add method (like DateTime.Add). That is a far more friendly name.

agent-j
  • 27,335
  • 5
  • 52
  • 79
  • Thanks for the ideas. But none of these seem strong enough to _disallow_ it. 1. The special names can (and are even now) hidden from IntelliSense, so I don't think this is an issue. 2. It's about people who _want_ to use it. 3. It has been recommended from v1.0 that you add a corresponding 'normal' method if you define an operator. They even specified which name to use for which operator. – Jeffrey Sax Jan 11 '12 at 03:18