Initializing a property in a method called from the constructor

1 week ago 10
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"); } }

Guru Stron's user avatar

2 Comments

Should I consider inlining those methods for performance? I've heard the compilers will do it if it's worth it and we should rarely do it ourselves, is that true?

2025-11-27T16:48:03.987Z+00:00

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article