I'm fairly new to C# and I'm following this tutorial.
I've reached the part about get
and set
of private instances (using theirs example)
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
where I assume get
is used when we just do myObj.Name
and set is called when using myObj.Name = "something"
(right?).
They then further write that the code above can be shortend by doing
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
and this I don't get, since now we aren't modifying any private property (name
in the first code) but we just have one public property called Name
. If that is the case, that we just have public string Name
, then why would we need the {get;set}
, now that Name
is public? Shouldn't we be able to get and set it anyway?
EDIT
This question is not about what the get/set
method does but what problem the Name {get;set;}
solves instead of just making Name
public.
I'm not talking about if e.g get
returns only the first 3 letters of the Name
field, I'm talking about the litteral {get;set;}
i.e when nothing more than {get;set;}
is defined, and what problem that solves.
If Name {get;set;}
allows the user to alter the value of the auto-created private field _Name
when why even bother having the _Name
field? To me it looks like, I have a piece of paper that no one can see (private _Name
) but, you can just send me a mail asking for the content of the paper ( Person.Name
), and how you want it to be changed (with no restrictions) (Person.Name="Liam"
). Why wouldn't I just give you the piece of paper and let you read/write what you want (just make Name
public)?
The same way here, if there's no restrictions to {get;set;}
then intead of having those methods modifying the _Name
field why not just make Name
public and ommit the {get;set;}
part?
I'm aware that you can modify the get
or set
to do something specific, but that is not the question here. It is all about only the public string Name {get;set;}
.
So, in the code below (not if we tweak it, change it or anything, but the code as it stands) why would we use the get_setter_name
instead of just public_name
?
class Person
{
public string public_name;
public string get_setter_name
{
get; set;
}
}
class Progam
{
static void Main(string[] args)
{
Person person = new Person();
person.public_name = "Foo";
Console.WriteLine(person.public_name);
person.get_setter_name = "Bar";
Console.WriteLine(person.get_setter_name);
}
}