C# Help!

The getter for Customer Cust is trying to return a null object:
Code:
        ...
        private Customer theCust = null;

        public Customer Cust
        {
            get 
            {
                return theCust;
            }
        ...
        }
You could add a if(theCust== null) check and instantiate it just before returning theCust?

If I add that I no longer get the Null exception, however I do get stack overflow :/
 
post all of your code.

If you are getting a stack overflow, that's usually because you have infinite recursion such as:

Code:
public Customer Customer
{
  get
  {
    if (Customer == null)
      theCust = new Customer();
    return theCust;
  }
}

Note that it is using Customer (and therefore infinitely recurring on its self) and not theCust.

Are you even debugging these changes people are posting? It's getting frightfully annoying to continually read that you are posting these problems seemingly never having even tried to investigate them yourself first.
 
Last edited:
I am a total C# and debugging noob. Unfortunately my course and teachers were more interested in teaching us OO fundamentals instead of how to actually use VS and the debugging interface and general good practice.

We we just get dumped with some sample code and some briefs. I won't pretend for a single moment that I am a good programmer, unfortunately though I need to learn this :S
 
Add a breakpoint by clicking the left margin by some code which will get executed then use F10 to step through line by line.

A more tidy way of doing:

if (c.GetType() == typeof(Activity))

is

if(c is Activity)
 
It should be pretty simple to debug this.

First of all, work out the steps you take to make the application go wrong. Make sure you can reproduce the problem 100% of the time using these steps.

Then take a look at the full exception message you are being shown (and post it here while you are at it). It should tell you the line number on which the exception is being thrown.

Add a breakpoint to this line. Make sure you are running the 'Debug' build (not the 'Release' build) and do the steps to make it go wrong again. The debugger will pause on the breakpoint.

Then you can inspect the values of any variables on that line by hovering the mouse over them. If a null reference exception is being thrown then one of the variable will be null. Then you've just got to work out either why it hasn't been set to a value, or why you are using it if it hasn't been set yet.
 
A more tidy way of doing:

if (c.GetType() == typeof(Activity))

is

if(c is Activity)

Those two lines are actually not the same.
If c was an object of a type derived from Activity then if(c is Activity) would return true, but if (c.GetType() == typeof(Activity)) would return false.

Besides, we've already got rid of all the nasty type checking from his code now.
 
I am a total C# and debugging noob. Unfortunately my course and teachers were more interested in teaching us OO fundamentals instead of how to actually use VS and the debugging interface and general good practice.

We we just get dumped with some sample code and some briefs. I won't pretend for a single moment that I am a good programmer, unfortunately though I need to learn this :S

We appreciate that you are new to programming. But please appreciate that we are not here to do this for you. Please try and solve a problem before posting it, and please remember to post as much information as you can when/if you must post it.

Posting your code at every step is a good start so we can see what changes you made.
 
This is the details of the error it is giving.

With the breakpoint at the line where the null error is given
Code:
var line = Customer.Getline();

The line variable is null, and the Customer class is also null. So would I be right in saying that even-though I believe all the needed code is there, I am never instantiating an object of the customer class?
Code:
System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=SD2coursework
  StackTrace:
       at SD2coursework.FrmHolidayCamp.updateCustomerList() in G:\Assessment\WindowsFormsApplication1\FrmCampBookings.cs:line 45
       at SD2coursework.FrmHolidayCamp.button1_Click(Object sender, EventArgs e) in G:\Assessment\WindowsFormsApplication1\FrmCampBookings.cs:line 99
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at SD2coursework.Program.Main() in G:\Assessment\WindowsFormsApplication1\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
 
That stack trace says that the exception is happening in a method called updateCustomerList, which isn't in any of the code you have posted so far.

How are you getting that it's in Customer.GetLine()? :confused:

Can you post the entire code for FrmHolidayCamp.
 
HolidayCamp isn't a form its a class:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SD2coursework
{
    class HolidayCamp
    {
        /*
         * This class is used to hold a list of Holiday objects that make up the holiday camp:
         * The Holiday objects may be added through the addToCamp() method.
         * The car objects may be deleted tgrough the removeFromCamp() method 
         * Use the camp property to access the list of Holiday objects
         */ 

        private List<Booking> theCamp = new List<Booking>(); //The list of car objects being stored
        private List<Customer> custLog = new List<Customer>();
        public List<Booking> camp 
            /* The camp property. Note that you can only read it
             * use the addToCamp and removeFromCamp to update it
             */
        {
            get
            {
                return theCamp;
            }
        }

        public List<Customer> log
        {
            get
            {
                return custLog;
            }
        }

        public void removeFromCamp(Booking aHoliday)
            //Remove booking from camp
        {
            theCamp.Remove(aHoliday);
        }

        public void addbookToCamp(Booking aHoliday)
            //Add booking to camp
        {
            theCamp.Add(aHoliday);
        }

        public void removeCust(Customer aCust)
        {
            custLog.Remove(aCust);
        }

        public void addCust(Customer aCust)
        {
            custLog.Add(aCust);
        }
    }
}

And this is the Camp booking class:

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SD2coursework
{
    public partial class FrmHolidayCamp : Form
    /*
     * This is the main form for the booking system.
     * It allows the adding to new bookings to the system, and displaying them 
     * 
     */
    {
        private HolidayCamp myCamp = new HolidayCamp();
        //Holiday object used to store bookings

        private HolidayCamp cust = new HolidayCamp();

        public FrmHolidayCamp()
        {
            //Default constructor
            InitializeComponent();
        }


        private void updateBookingList()
        {   //Used to update the camp displayed on the form
            lstBookings.Items.Clear();
            foreach (var Booking in myCamp.camp)
            {
                var line = Booking.GetLine();
                lstBookings.Items.Add(line);
            }
        }
       private void updateCustomerList()
       {
            lstCustomers.Items.Clear();
            foreach (var Customer in cust.log)
            {
                var line = Customer.Getline();
                lstCustomers.Items.Add(line);
            }
        }

        private void btnAddBooking_Click(object sender, EventArgs e)
        {
            //Add a new Booking
            FrmBooking bookingGui = new FrmBooking();   //Form used to add new Holiday
            bookingGui.ShowDialog();
            Booking myHoliday = bookingGui.booking;         //Get new holiday from form
            myCamp.addbookToCamp(myHoliday);               //Add to camp list
            updateBookingList();                      //Uodate camp list
        }

        private void lstBookings_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*
             * This method is used to control the list box
             * It is called when a row is selected by the user, it then displays frmBooking
             * with the booking details
             */
            if (lstBookings.SelectedIndex > -1)
            {
                int index = lstBookings.SelectedIndex;
                Booking myBooking = myCamp.camp.ElementAt(index);
                FrmBooking bookingGui = new FrmBooking();
                bookingGui.booking = myBooking;
                bookingGui.ShowDialog();
                updateBookingList();

            }
        }

        private void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstCustomers.SelectedIndex > -1)
            {
                int index = lstCustomers.SelectedIndex;
                Customer myCust = cust.log.ElementAt(index);
                FrmCustBooking CustGui = new FrmCustBooking();
                CustGui.Cust = myCust;
                CustGui.ShowDialog();
                updateCustomerList();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FrmCustBooking CustGui = new FrmCustBooking();   //Form used to add new Holiday
            CustGui.ShowDialog();
            Customer myCust = CustGui.Cust;         //Get new holiday from form
            cust.addCust(myCust);               //Add to camp list
            updateCustomerList(); 
        }
    }
}
 
OK, I think I see what's going on. It's a little confusing how you've done the code, but from what I can see FrmCustBooking sets the backing field for the Cust property when it's closed.
You then get this property in the calling method and add it to the list.

Personally I'd think about re-writing how you do that, but to get you going a bit quicker you want to step through the bits where it's setting the property.

If you put a breakpoint on the line where it reads the property is it null there? (I assume it will be.
Code:
Customer myCust = CustGui.Cust;         //Get new holiday from form

Have you tried putting a breakpoint on the closing event handler to ensure that's getting called properly? This would be the first thing I'd do to make sure the code is actually setting the property.
 
An ENORMOUS thanks to Pho for solving my problem in like a minute, if that.

I mailed him the code today to look over and he got it straight away.

I hadn't associated (if that's the right word) my whole FrmCustBooking_Closed thing with actually closing the form, so it was never being ran, so Customers were never being instantiated and nulls were always being thrown.

My apologies for wasting all your time with my ludicrous problems, I certainly need to look into debugging best practice. I promise next time I post on here I'll be better :D

Thanks to all of you, and especially Pho, you guys are awesome :)
 
Back
Top Bottom