ARTICLE AD BOX
Can I add an attribute to MyMethod to tell the compiler don't worry this is only called in constructors?
No. There is no such attribute, at least at the moment.
I would argue that you should just initialize data in the constructor.
If you still want methods - you can use return values. For example:
public class MyClass { private string Name { get; init; } public MyClass() { Name = MyMethod(); } public string MyMethod() { return "Hello"; } }Or value tuples for multiple values:
public class MyClass { private string Name { get; init; } private string World { get; init; } public MyClass() { (Name, World) = MyMethod(); } public (string Name, string World) MyMethod() { return ("Hello", "World"); } }150k11 gold badges186 silver badges232 bronze badges
2 Comments
When talking about performance you need to measure (benchmark and find hot paths). If you have A LOT of such ctor calls probably this will have a positive effect though 1) highly likely compiler will take care of it 2) extra uninlined method call will not be the biggest of your problems - GC will. "I've heard the compilers will do it if it's worth it and we should rarely do it ourselves, is that true?" - that's the general rule of thumb, yes. So to sum it up - you should not bother unless proven otherwise.
2025-11-27T16:52:06.937Z+00:00
Explore related questions
See similar questions with these tags.

