Click here to Skip to main content
15,881,630 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends! I am currently learning C# and I have tried everything to create a User Input Array. All the solutions I have seen on the web and coding structures result in Null Reference Assignments. csharp(CS8601) I do not understand what is causing the issue.

static void Main(string[] args)
      {
        Console.ReadKey();
        
        {
            Console.WriteLine("Type in Three baseline's:");
            string[] baseline = new string[5];

            for (int i = 0; i < baseline.Length; i++)
            {
                baseline[i] = Console.ReadLine();
            }



Appropriate close {} were used, but it is not translating well into the text box here. Any suggestions?

image-2022-01-21-193459 — ImgBB[^]

What I have tried:

I have tried both a for loop as well as individual Readline statements for each variable response in the array.
Posted
Updated 21-Jan-22 15:46pm
v2
Comments
Richard Deeming 24-Jan-22 8:37am    
NB: The code in your question asks the user to type in three values. The code in your screenshot asks them to type in six values. In both cases, you expect them to type in five values.

1 solution

I guess you are in the following situation:
- using Visual Studio 2022 (no problem)
- targeting .NET 5 or 6 (and not .NET Framework 4.xxx) (no problem)
- building with project setting: Build/General/Nullable: enable (is the default) AHA
- and probably: treat warnings as errors (is often a good idea)


Which would mean you're using C# 8.0 or higher, which has a new feature (possible null testing) resulting in a warning/error when a reference might be or become null.

Here Console.ReadLine() returns null on end-of-input, and the destination was declared array of string, not array of string? (the ? being the newest thingy indicating you would accept null values).

I haven't investigated yet, I'm not sure how useful the new feature could be. IMHO it is a breaking change, however it can easily be fixed by changing the conditions I mentioned earlier.
The most obvious one would be: Nullable: disable

:)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900