[SourceGen][Proposal] Consider simplifying generated setters using C#14 null conditional assignment
- Dominant language
- C#
- Stars
- 23.3k
- Forks
- 2k
- Avg merge
- 1d 14h
- Merged PRs (30d)
- 296
Description
Consider the following scenario:
```c#
// The binding
label.SetBinding(Label.TextProperty, static (VM vm) => vm?.B?.C);
// We generate
setter = static (source, value) =>
{
if (source is {} p0
&& p0.B is {} p1)
{
p1.C = value;
}
};
// In C# 14 we could generate just
setter = static (source, value) => source?.B?.C = value;
```
In C# 14, the compiler can do this for us: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14#null-conditional-assignment. Migrating to this feature will reduce the complexity of our codebase and also avoid hitting any edge cases we might not be aware of.
There is a problem though and that's accessing and setting directly inaccessible properties. Because we have to generate the interceptor method in the case of `SetBinding` in different location, we need to use `[UnsafeAcceesor]` to work around that limitation. This might also mean that we would need 2 different codepaths - one for the "typical" scenario, where we can use C#14, and one for the more complicated scenario with unsafe accessors, which means keeping what we have today. If we need to have 2 different implementations, it would defeat the original intent. There is also the concern of "forcing" the developer to use C# 14+, although I'm not convinved that is would be a dealbreaker.
There is nothing forcing us to rewrite the setter generator and this issue is more for me not to forget to look into this at some later point 😄
Contributor guide
Research direction
Start by locating the SourceGen setter generator and its SetBinding path, then compare the typical generated setter with the UnsafeAccessor case described here. Check the C# 14 null-conditional assignment requirements and determine whether both access paths can be supported without forcing an incompatible language version. Done means the approach and its edge cases are resolved.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- tooling
- Issue type
- Refactor
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100