Skip to content

Instantly share code, notes, and snippets.

@controlflow
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save controlflow/9996665 to your computer and use it in GitHub Desktop.
Save controlflow/9996665 to your computer and use it in GitHub Desktop.
Possible C# primary constructors design
class Person : EntityBase {
// ~familiar syntax, no problems with xml doc, can omit body, can omit public?
public constructor(int id, string name, int age) : base(id);
readonly string _mrName = "Mr. " + name;
public string Name { get; } = name;
public int Age { get; } = age;
}
class Person {
// can change visiblity and add body for checks
private constructor(string name, int age) {
if (name == null) throw new ArgumentNullException("name");
}
public Person() : this("Foo", 42) {
// secondary
}
public string Name { get; } = name;
public int Age { get; } = age;
}
class Component {
// explicit capture, can omit private when readonly
[ImportingConstructor] // no problems with attributes
public constructor([NotNull] readonly IFoo foo, [NotNull] readonly IBar bar);
public IFoo ExposedFoo => foo;
public void M(foo) {
// capture declares ordinary fields from class parameters,
// so conflicts with locals can be resolved by 'this.' qualifier
... this.foo ...
... bar ...
...
}
}
// placing primary constructor inside class body prevents from ability to put tons of code
// outside of class declaration body block, keeping class name and extends clause clear.
// I'm expecting silly classes like this:
class Component(IFoo dependency, IBar other, IBlah anotherOne)
: MySuperBaseType(dependency, other, anotherOne, (HowPeopleLove to) => {
put.LambdaExpressions(Inside.Base.Initializer);
InsteadOfOverridingMethods();
HowIHateThis();
}), ISomeInterface, IOtherInterface
{
}
@ashmind
Copy link

ashmind commented Apr 6, 2014

In general I see primary constructors as something similar to autoproperties -- they are not a silver bullet for everything.
If you need something uncommon such as private constructor or event subscription in constructor, you can fall back to using normal constructor. Though if second part is common, it can be done by allowing a code block one way or another. I am just not sure it is common.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment