-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Champion "ref extension methods on structs" (C# 7.2) #186
Comments
Very important feature |
Precedent in VB.NET. Should be compatible? (Currently C# can't see VB.NET's byref extension methods) Also should work with ref returns; which enables low cost fluent or functional struct apis |
See also #128 (ref operators (on structs)) |
What happens if we have two overloads, void Deconstruct<T, U>(in this KeyValuePair<T, U> k, out T key, out U value) { .. }
void Deconstruct<T, U>(this KeyValuePair<T, U> k, out T key, out U value) { .. } I think this should be possible to provide a ref variant without breaking existing code and the compiler should prefer the first overload afterwards. |
I think it could be amend this case by having compiler enforce that, extension method must not assign a possible null value into the The ability to mutate reference type make it easy to write a lazy initializing or conditional caching public static class Ext
{
public void InitializeIfNull<T>(ref this T obj) where T : ICanInitial // some interface for initializing pattern
{
if(obj != null)
return;
// initialize obj by ICanInitial pattern
}
}
public class SomeClass : ICanInitial
{
public static DerivedSomeClass _instance;
public static DerivedSomeClass Instance => _instance.InitializeIfNull();
} And we must always check that it will not be null anytimes in that function public static class Ext
{
public T InitializeIfNull<T>(ref this T obj) where T : ICanInitial // some interface for initializing pattern
{
if(obj != null)
return;
obj = GetFromSomeWhere(); // ERROR it might be null
if(GetFromSomeWhere() is var got && got != null)
obj = got; // not null by flow analysis
obj = GetFromSomeWhere() ?? obj; // should not error, it never change from object to null, worst case is null to null
}
} |
Would it make sense to include this on extension methods for other immutable types like delegates as well? |
If you want to propose that, I would suggest opening a new issue. This shipped a few years ago and is just waiting to be added to the ECMA spec. |
See also dotnet/roslyn#165
The text was updated successfully, but these errors were encountered: