Share via

What is late variable initialization?

YHY 41 Reputation points
Apr 22, 2021, 4:45 AM

I need your help! I would appreciate that :)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,318 questions
0 comments No comments
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,636 Reputation points
    Apr 22, 2021, 5:41 AM

    Hi YHY-1161,
    Normally, properties or variables declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.
    To handle this case, you can use "late variable initialization".
    It means that you do not initialize objects until the first time they are used. Typically, this comes about when you are unsure of what initial value an instance variable might have but want to provide a default. Rather than initialize explicitly in the constructor (or class static initializer), it is left until access time for the variable to be initialized, using a test for null to determine if it has been initialized.
    Ella Gogo's answer will help you understand it better.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.