简体   繁体   中英

C#: throwing exception Value cannot be null for list<int>

Test function returning null when user input is 10. please guide me how to handle this situation

List<int?> test10 = testInt(9, 10).ToList();

public static List<int?> testInt(int pagetotal, int userinput)
{
    List<int?> _data = null;

    if (userinput <= 10 && userinput != 0)
    {
        if (userinput <= pagetotal)
        {
            _data = Enumerable.Repeat(pagetotal / userinput, userinput - 1).ToList();
            int y = (pagetotal - pagetotal / userinput * (userinput - 1));
            _data.Add(y);

        }
    }

    return _data;
}

_data is set to a non- null value only when all these conditions are true :

  • userinput <= 10 - this is true , because userinput is 10
  • userinput != 0 - this is true , because userinput is 10
  • userinput <= pagetotal - this is false , because userinput is 10 while pagetotal is 9

You need to decide what to return when pagetotal is less than userinput . Currently it is null , but you could potentially return an empty list:

if (userinput <= pagetotal) {
    ...
} else {
    _data = ...
}
userinput <= pagetotal

That part prevents _data from being initialized if userinput >=10 (with pageTotal=9). I think it is better to normalize userinput first. You can add following line:

if(userInput > total)
    userInput = total;
if(userInput <1)
    userInput =1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM