Thomas
Thomas

Reputation: 1126

null reference exception error for my windows form app

I have a Setting.cs file containing the info

[Serializable]
public class Setting
{
    public Setting()     {}

    public String defaultAlertTone = Path.GetDirectoryName(Application.ExecutablePath) + "\\Sounds\\applause-2.wav";        
}

and my settingsForm retrieving the info through this code

Setting settingObject;
public SoundPlayer player;

public settingsForm(backgroundForm backgroundFormObject)
{
    InitializeComponent();
    this.backgroundFormObject = backgroundFormObject;
    settingObject = backgroundFormObject.getSetting();
}

private void InitializeSound()
{
    // Create an instance of the SoundPlayer class.
    player = new SoundPlayer();
    player.SoundLocation = settingObject.defaultAlertTone;

    // Listen for the LoadCompleted event.
    player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted);

    // Listen for the SoundLocationChanged event.
    player.SoundLocationChanged += new EventHandler(player_LocationChanged);
}

Why is it that every time I run the app, there would be a null reference exception on the

player.SoundLocation = settingObject.defaultAlertTone;

the backgroundFormObject.getSetting(); is just a method to retrieve the setting object. the code for it are as follows

Setting settingObj = new Setting();

public Setting getSetting()
    {
        return settingObj;
    }

Upvotes: 0

Views: 339

Answers (1)

abhinav
abhinav

Reputation: 3217

The reasons could be

  1. InitializeSound() is somehow running before settingsForm (not likely, but this would make the settingObject not initialized and refer to null).
  2. If this is the complete code for Setting class, i don't see how calling new Setting() anywhere would make a difference. So use Setting settingObject = new Setting(); when you first define this property in the settingsForm class.
  3. It is not the settingObject which is null.

Upvotes: 2

Related Questions