Skip to content
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

Reduce visual noise with primary constructors #611

Closed
Head0nF1re opened this issue Jan 30, 2024 · 1 comment · Fixed by #612
Closed

Reduce visual noise with primary constructors #611

Head0nF1re opened this issue Jan 30, 2024 · 1 comment · Fixed by #612
Assignees
Milestone

Comments

@Head0nF1re
Copy link
Contributor

Primary constructors were introduced in C# 12, we should consider replacing the normal flow of adding a ctor in order to initialize fields. This would reduce some visual noise, just need to be aware of double capturing.

With primary constructors, AKA parameters for classes, we would be able to do:

this

private sealed class ExcludeCollectionIterator<T>(
	ICollection<T> source,
	int startIndex,
	int count) : CollectionIterator<T>
{
	public override int Count =>
		source.Count < startIndex ? source.Count :
		source.Count < startIndex + count ? startIndex :
		source.Count - count;

	protected override IEnumerable<T> GetEnumerable() =>
		ExcludeCore(source, startIndex, count);
}

instead of

private sealed class ExcludeCollectionIterator<T> : CollectionIterator<T>
{
	private readonly ICollection<T> _source;
	private readonly int _startIndex;
	private readonly int _count;

	public ExcludeCollectionIterator(ICollection<T> source, int startIndex, int count)
	{
		_source = source;
		_startIndex = startIndex;
		_count = count;
	}

	public override int Count =>
		_source.Count < _startIndex ? _source.Count :
		_source.Count < _startIndex + _count ? _startIndex :
		_source.Count - _count;

	protected override IEnumerable<T> GetEnumerable() =>
		ExcludeCore(_source, _startIndex, _count);
}

The only issue is that primary constructors params can't be readonly, the solution would be to choose one option:

  1. Initialize a private readonly field, still reducing code by removing the ctor.
  2. Ignore it.

My purist side says "initialize the readonly fields", while my practical side says to just ignore it. What do you think?

@viceroypenguin
Copy link
Owner

For SuperLinq, I think we can get away with 2. ignoring it. And as far as double-capturing goes, we can just turn some of the compiler warnings for primary constructors into errors. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/constructor-errors#primary-constructor-declaration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants