Below is a very basic program with three classes which makes use of an Indexer to search for a person within a List<> per based on their age.
Person.cs Below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Indexer1
{
public class Person
{
private string name;
private string surname;
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public override string ToString()
{
return string.Format("{0} {1} {2}", name, surname, age);
}
public Person(string name, string surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
}
}
Indexer.cs instantiates Person in List<> per Below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Indexer1
{
public class Indexer
{
List<Person> per = new List<Person>();
public Indexer()
{
per.Add(new Person("Joe", "Soap", 25));
per.Add(new Person("Marry", "Jane", 82));
per.Add(new Person("Garry", "Zuma", 37));
per.Add(new Person("Nelson", "Mabaso", 14));
}
public Person this[int indexes]
{
get
{
foreach (Person item in per)
{
if (item.Age == indexes)
{
return item;
}
else
{
return null;
}
}
return null;
}
set
{
per[indexes] = value;
}
}
}
}
Program.cs instantiates the indexer to allow for search and find, Below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Indexer1
{
class Program
{
static void Main(string[] args)
{
Indexer ind = new Indexer();
Console.WriteLine("enter in age of person you are searching for");
int age = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("{0} {1} {2}", ind[age].Name, ind[age].Surname, ind[age].Age);
Console.ReadKey();
}
}
}
When I run the program and search for the first person added to the List<> per "Joe Soap" by entering in his age: 25 when prompted, I am able to find him successfully and display all his info.
But as soon as I search for anyone else in the List<> per, let's say "Garry Zuma" by entering in his age: 37 when prompted, the program fails and throws an exception:
An unhandled exception of type 'System.NullReferenceException' occurred in Indexer1.exe Additional information: Object reference not set to an instance of an object.
I have tried searching on that exception but I couldn't find anything that solved my problem.
Your guys help and assistance is much appreciated.