Click here to Skip to main content
15,895,988 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
C#
public partial class MainWindow : Window, INotifyPropertyChanged
{
    List<string> _firstNo = new List<string>();
    List<string> _secondNo = new List<string>();
    
    int i=0;
    
    string name;

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }
    public string FirstNo
    {           
        get
        {
            return _firstNo[i];  //getting an error on this line
        }
    }

hey guys. I am learning C# and just came across lists. I want to return one element of my list "_firstNo" . But the compiler throws an exception saying "Index was out of range. Must be non-negative and less than the size of the collection." .

Thanks in advance. :)
Posted
Updated 25-Jul-12 0:44am
v4
Comments
sjelen 25-Jul-12 6:42am    
Have you added any strings to the list before you try to use FirstNo?

Until you add an element to the list, you will always get an error when you try to access any element at all.
Check first:
C#
if (_firstNo.Count > i)
   {
   return _firstNo[i];
   }
return null;
You might want to consider throwing an exception instead of returning a null value, or return an empty string - it depends on how you are going to use the result.
 
Share this answer
 
Comments
_Amy 25-Jul-12 6:53am    
My +5! Correct. If the number of items is more than 0 then only return _firstNo[i] otherwise return null..
sandeep nagabhairava 25-Jul-12 6:59am    
my 5!
BillW33 25-Jul-12 10:00am    
Very nice answer, +5
List<string> _firstNo = new List<string>();
You created an object of list of strings.
But it is empty. Nothing is assigned to it.
Here you are trying to access the "i"th (which is 0 in you code) positioned item from the list. The list is empty. That's why error is coming.

Happy Coding :)
 
Share this answer
 
It simply means that for whatever value of 'i' you are sending the call to access FirstNo, the list _firstNo does not have it.

For example, you tried to access FirstNo when i was 0, then FirstNo = _firstNo[0];
Now, if the list _firstNo, has atleast one element in it then it will go fine or else index out of range error will be raised.

If you fail to add anything to list and try to access even index 0, you will get the error for accessing 0th index.
 
Share this answer
 

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