Reputation: 31
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!
Upvotes: 2
Views: 3014
Reputation: 9804
I can not figure it out either. As it is written now, the result of the if will always been overwritten by name = value;
. Honestly it is likely that the JiT's dead code detection might notice that one and just cut out the if entirely. Unless he is planning to teach you about that one, I seen no point in this code.
Also the return value of value.Any(char.IsDigit)
is inverted, wich is propably the last thing you should be doing there. Really, unless he was trying to teach you debugging or is live coding, I see no way this could work.
The closest sensible code I can make of it is:
if (value.Any(char.IsDigit))
{
name = "No Name";
}
else{
name = value;
}
Upvotes: 4