Reputation: 159
I have a public class called Profile
. Very simple model class currently with 2 properties; string Name
and string Fields
. As I develop the project the class will expand but it's not particularly important at the moment.
I have a Global static IList
of type Profile
called Profiles
. I am quite new to manipulating the data in these IEnumerable
types but I am looking to update one of the properties of a single profile. I have tried the following but I am receiving an object reference not set exception. The following is where I set the property:
Profiles.Single(x => x.Name == listBoxProfiles.Text).Fields = textBoxFieldName.Text;
The debugger is showing the listbox and textbox text properties both have the correct values so I think that it is the way I am using single that is wrong.
If anyone could shed some light I would be grateful.
Upvotes: 3
Views: 170
Reputation: 64487
A simple amendment to make the code more defensive is all that is required:
var profile = Profiles.SingleOrDefault(x => x.Name == listBoxProfiles.Text);
if (profile != null)
{
profile.Fields = textBoxFieldName.Text;
}
else
{
Profiles.Add(new Profile(textBoxFieldName.Text));
}
This code will cope with missing values, SingleOrDefault
expects 0 or 1 items to be returned. It will throw an exception if more than 1 items are found.
If you know your code should always have the item you are looking for, then your code will work - but I'd advise against this style of programming in favour of being a little more defensive.
Upvotes: 1