Allow by-ref Extension methods.
See original GitHub issueCurrently C# allows methods that are public and static on static classes to be extension methods by augmenting the first parameter with the this
keyword.
This is all well and good, but structs cannot really benefit from this feature as much as struct method invocation is basically always by-ref. e.g. Calling 3.GetHashCode() actually translates in il like…
ldc.i3
stloc.0
ldloca.s 0
call Int32 GetHashCode
(Forgive me if that’s wrong its from memory.) The basic gist here is that we actually get a reference to the memory location and then invoke the method. My proposal is to allow a user to declare extension methods with a by ref first parameter if it is a struct. Thus:
public static void MyMethod(this ref int x){...} // allowed
public static void MyMethod<T>(this ref T x) where T:struct //allowed
public static void MyMethod(this ref string x) // not allowed.
Technically, I suppose we don’t need to restrict it. But I think the behavior isn’t as necessary for class types.
This would be a large benefit for larger structs as copying them is something you always would want to avoid.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:40
- Comments:25 (16 by maintainers)
Top GitHub Comments
The following is valid code:
The following should be valid as well, with exactly the same result:
This feature would only encourage mutable structs, which are almost always a bad idea.