Skip to content

Allow by-ref Extension methods. #165

@mburbea

Description

@mburbea

Currently 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.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions