Question

class Customer
{
 public string name;
 public sting nic;
 public int age;

 public void add_customer()
    {
        // some code here to assign the values to the data types
    }
}

class main_menu
{
   Customer[] cust = new Customer[100];
   // some other data members

   public void new_customer()
   {
      // Some Console.WriteLine pritings
      cust[0].add_customer();
      // ------>> Now here in this line error is arrising which says
      An unhandled exception of type 'System.NullReferenceException' occurred in   Assignment 2.exe

      Additional information: Object reference not set to an instance of an object.


   }
}

Now what i want to do is to Fill the data variables in arrays of objects one by one in all the customers instances

Kindly help me because i am beginner

Was it helpful?

Solution

cust[0] is null thus trying to access one of his properties or methods before assigning it a value will cause this exception.

You main misunderstanding - by initializing cust you didn't initialized any one of the objects in it ( cust[i] will be null for every i).

You need to validate it before using it:

class main_menu
{
   Customer[] cust = new Customer[100];
   // some other data members

   public void new_customer()
   {
    cust[0] = new Customer();

      // when you want to use it later on, do this validation.
    if (cust[0] != null)
    {      
        cust[0].add_customer();
    }
   }
}

OTHER TIPS

In your code, you generate a collection to hold 100 customer objects, and then you are attempting to populate the fields of the first customer, but in the collection it does not exist yet. Idiomatically in C# we generate an empty collection, and then populate this collection with fully initialized Customer objects. Something like:

public class main_menu
{
  List<Customer> customers = new List<Customer>(); // empty collection of Customer's
  public void new_customer(string name, string nickname, int age)
  {
    customers.Add( new Customer { name, nickname, age } );
  }
} 

You should see two news, one for the collection, and one for each of the (reference) objects inserted into the collection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top