Hello there fellow friends. I have a small problem with auto properties. I'm new to programming in general and I've only started learning about classes and objects. When I try to use auto properties, the field does not get exposed. (not sure if thats the right way of putting it) Take a look at the commented parts of the Properties in both animal Classes to understand what I'm talking about.
Right now I have this Animals Class
public class Animals
{
//fields
private string name;
public Animals(string name)
{
this.name = name;
}
// default constructor
public Animals()
{ }
//This is the problematic portion
public string Name { get; set; }
public void Bark()
{
Console.WriteLine("{0} said WoWOW", name);
}
}
This is my main program class
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Animals dog = new Animals(name);
dog.Bark();
Animals cat = new Animals();
Console.WriteLine("Enter second name: ");
cat.Name = Console.ReadLine();
cat.Bark();
}
}
The output is as follows. The last Line is my problem
Enter name:
bob
bob said WoWOW
Enter second name:
sarah
said WoWOW //sarah is missing here
However when i change the properties from {get;set} to its full version in the class. It outputs the correct output.
edited code
public class Animals
{
//fields
private string name;
public Animals(string name)
{
this.name = name;
}
public Animals()
{ }
//apparently this is the correct way of making properties
public string Name
{
get { return name; }
set { name = value; }
}
public void Bark()
{
Console.WriteLine("{0} said WoWOW", name);
}
}
output: //Sarah is present in the last line
Enter name:
bob
bob said WoWOW
Enter second name:
sarah
sarah said WoWOW
My question is: Why is it when auto properties is used I do not get my desired output but when i write the properties in full I do get my desired outcome. Thanks for taking a look at my question. Hopefully it wasn't too long! ;]