Mia .B Mia .B - 1 month ago 7
C# Question

Windows Forms, Set method throws string.isnullorempty exception? C#

This a class which holds the value of first and last name.
Another class called attendee inherates from person.

class Person
{
static private string FirstName;
static private string LastName;

static public string firstname
{
get
{
return FirstName;
}
set
{
if(string.IsNullOrEmpty(FirstName))
{
throw new ArgumentException("First name must not be blank!");
}
FirstName = value;
}
}


This is in my GUI class and the method retrieves the value of the first name and updates it within the Person class.

private void BtnSet_Click(object sender, EventArgs e)
{
Attendee.firstname = FirstName.Text;
... //more code (not relevant)
}


For some reason this throws the exception from the Person class but I do not understand why?

L.B L.B
Answer

You check the FirstName field which is initially null in the setter of firstName property, use instead

 set
 {
     if(string.IsNullOrEmpty(value))
     {
         throw new ArgumentException("First name must not be blank!");
     }
     FirstName = value;
 }
Comments