vendredi 25 octobre 2019

C# Setter and if statement

I've been watching a tutorial about OOP in C#.

I don't understand why the assignment of the value to the name inside of a Name property isn't inside of else-clause.

class Animal
{
    private string name;
    protected string sound;

    public Animal()
        :this("No Name", "No Sound") { }

    public Animal(string name)
        :this(name, "No Sound") { }

    public Animal(string name, string sound)
    {
        Name = name;
        Sound = sound;
    }

    public string Name
    {
        get { return name; }

        set
        {
            if (!value.Any(char.IsDigit))
            {
                name = "No Name";
            }
            name = value;


        }
    }

    public string Sound
    {
        get { return sound; }

        set
        {
            if (value.Length > 10)
            {
                sound = "No Sound";
            }
            else
            {
                sound = value;
            }
        }
    }

    protected AnimalIDInfo animalIDInfo = new AnimalIDInfo();

    public void SetAnimalIDInfo(int idNum, string owner)
    {
        animalIDInfo.IDNum = idNum;
        animalIDInfo.Owner = owner;
    }

    public void GetAnimalIDInfo()
    {
        Console.WriteLine($"{Name} has the ID of {animalIDInfo.IDNum} and is owned by {animalIDInfo.Owner}");
    }

    public void MakeSound()
    {
        Console.WriteLine($"{Name} says {Sound}");
    }


}

}

Could someone explain me this, please? Isn't this code going to always assign a value to the name no matter of the if statement?

On the other hand, when I tried with an else clause then I get "No Name" even if the value i'm passing doesn't contain any digits.

Here is the Main method:

static void Main(string[] args)
    {
        Animal whiskers = new Animal()
        {
            Name = "Whiskers",
            Sound = "Meow"
        };

        Dog grover = new Dog()
        {
            Name = "Grover",
            Sound = "Woof",
            Sound2 = "Grrrr"
        };

        grover.Sound = "Woooooooof";

        whiskers.MakeSound();
        grover.MakeSound();

        // Inheritance has an "is a" relationship ("A dog IS AN animal")

        // aggregation or a delegate represents "has a" relationship

        whiskers.SetAnimalIDInfo(12345, "Sally Smith");
        grover.SetAnimalIDInfo(12346, "Paul Brown");

        whiskers.GetAnimalIDInfo();
        grover.GetAnimalIDInfo();




    }

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire