Where is Initialization code in this Leetcode solution for Two Sum

Viewed 23

I'm not asking about this line ->
Dictionary<int, int> resultDictionary = new(); according to my knowledge this line initialize an empty Dictionary, so where does the data that the TryGetValue Method checks against come from? in this line ->
if (resultDictionary.TryGetValue(secondNumber, out int index))

The following code contains Dictionary declaration but what is wondering me is the absence of populating Dictionary with data. Can anyone explain what's going on here?

public class Solution {
    public int[] TwoSum(int[] nums, int target) 
    {
        //Declarations
            int arrayLength = nums.Length;
            Dictionary<int, int> resultDictionary = new();
            
            //Validations
            if (nums == null || arrayLength < 2)
            {
                return Array.Empty<int>();
            }

            //Logic
            for (int i = 0; i < arrayLength; i++)
            {
                int firstNumber = nums[i];
                int secondNumber = target - firstNumber;
                
                if (resultDictionary.TryGetValue(secondNumber, out int index))
                {
                    
                    
                    return new[] { index, i };
                }

                //resultDictionary.Add(firstNumber, i);
                resultDictionary[firstNumber] = i;
                //Console.Write(resultDictionary[firstNumber]);
            }

            return Array.Empty<int>(); 
        
    }
}
1 Answers

The code uses a C# version 9 language feature, called target-typed new. You can have more information here

Related