Why isn't my property doing the check?

102 views Asked by At

My constructor get info from the form. The 'name' is addressed with 'aName' (from the constructor), then there has to be a check done with prop 'NameCheck'. but if I compile it, it return an empty string. Any ideas?

Code:

---- Class ----

//Fields
private List<Create> Characters;
private string name;
private int health;
private int mSpeed;
private Role role;
private Speciality speciality;

//Properties
public string NameCheck
{
    get {
        return name;
    }
    set
    {
        if (string.IsNullOrEmpty(name))
        {
            name = "Name not specified";
        }
        else 
        {
            name = value;
        }
    }
}

//Constructor

public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
    this.name = aName;
    this.health = aHealth;
    this.mSpeed = aMSpeed;
    this.role = aRole;
    this.speciality = aSpeciality;

    Characters = new List<Create>();
}

---- Form ----

Create character = new Create(tbName.Text, health, mspeed, aLane, aSpecial);

Characters.Add(character);

cbSummary.Items.Add(character.ToString());

PS: cbSummary is a combobox.

EDIT:

public override string ToString()
{
    return "Name: " + NameCheck + " - Health: "  + health + " -  MovementSpeed: " + mSpeed + " - Role: " + role + " - Speciality: " + speciality;
}
3

There are 3 answers

1
Hamid Pourjam On BEST ANSWER

You should set this.NameCheck instead of this.name in your constructor

public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
    this.NameCheck = aName;

also you should check value for emptiness or being null instead of name in your property setter

set
{
    if (string.IsNullOrEmpty(value))
    {
1
Paddy On

You have a small typo in your property:

public string NameCheck
{
    get {
        return name;
    }
    set
    {
        // You need to check value, not name.
        if (string.IsNullOrEmpty(value))
        {
            name = "Name not specified";
        }
        else 
        {
            name = value;
        }
    }
}
1
Jurgen Camilleri On

In your constructor you should use your NameCheck property rather than the name field:

public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
    this.NameCheck = aName;
    this.health = aHealth;
    this.mSpeed = aMSpeed;
    this.role = aRole;
    this.speciality = aSpeciality;

    Characters = new List<Create>();
}

Also as Paddy said you are doing an incorrect check in the set body of NameCheck:

public string NameCheck
{
    get
    {
        return name;
    }
    set
    {
        if (string.IsNullOrEmpty(value))
        {
            name = "Name not specified";
        }
        else 
        {
            name = value;
        }
    }
}