0

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);

    }

}

CutePoison
  • 4,679
  • 5
  • 28
  • 63
  • Look at [SharpLab](https://sharplab.io/#v2:EYLgZgpghgLgrgJwgZwLRIMYHsEBNkA0uIA1AD4ACATAIwCwAUI9QAQAKECyWAdowN6MWLCgGYRNAAwsAclAC2EFvxYBzCDADcLZBu0BfRvqA===). Compiler-generated code is on the right. – ProgrammingLlama Oct 03 '22 at 04:48
  • The answers there doesn't really answer why we just don't make `Name` public i.e how `public string Name {get;set}` differs from `public string Name` since `get` returns `Name` and `set` modifies `Name`. I.e what difference the `set` method do when we call `Person.Name="Liam"` compared to not having it? Some write that there isn't then a private `name` attribute that is created, which makes if difficult for me to understand the useage of `{get;set}` – CutePoison Oct 03 '22 at 04:57
  • Perhaps this answers that aspect?: https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property – ProgrammingLlama Oct 03 '22 at 04:59
  • It is still the same; no one explains *when* it differs i.e what is the application difference between doing `Car.N_wheels = 10; Console.WriteLine(car.N_wheels)` using `public int N_wheels{get;set;}` and just `public int N_wheels`? I totally get that we can set/get some values using the `{get;set;}` but so can we just omitting it? And since we aren't reading/changing any private/other field with just `{get;set;}` then why use it? – CutePoison Oct 03 '22 at 05:14
  • 1
    The thing you're missing is that your two code snippets are the same. They both compile to basically the same result. It's just that the private field is implicit in the second code snippet, so that you don't have to type as much. Always expose data publicly via properties. Auto-properties are a way to reduce the amount of code required to do that in simple cases. – jmcilhinney Oct 03 '22 at 05:14
  • 1
    *"since we aren't reading/changing any private/other field"*. We are. That's the point. You don't see it in your code but it's there. This is what's referred to as "syntactic sugar". If you pay attention to Intellisense when it lists the members of your type, you'll see a field whose name matches your property with an underscore prepended. That is the implicit field. – jmcilhinney Oct 03 '22 at 05:17
  • Okay, so we actually get a private field in the class called `_name` that the class can access internally? And if we do, why not just make `Name` public since we can alter `_name` anyway using the `Name` field? I just really struggle to understand what problem the `Name {get;set;}` solves? To me it just looks like we create uneeded more code, since `Name` now allows the code to change/get `_Name` thus why not just make `Name` public? I can see usecase when `get` or `set` is defined to e.g return only the firstname but when it returns everything anyway then... – CutePoison Oct 03 '22 at 05:19
  • @ProgrammingLlama I have editted my question accordingly – CutePoison Oct 03 '22 at 05:29
  • This: https://stackoverflow.com/questions/4142867/what-is-the-difference-between-a-property-and-a-variable ? – Rand Random Oct 03 '22 at 05:38
  • The main point in my opinion, is for the sake of encapsulation([link](https://en.wikipedia.org/wiki/Encapsulation_(computer_programming))), as it just provides an easier, less messy way of writing the usually get/set method as you would be doing in fx. java or the like. The tl;dr: is that you shouldn't expose public fields outright, and properties solve that in a simple way, as well as giving you an easy way to operate on that data when you set or get the value. – A Sad Shoe Oct 03 '22 at 05:40
  • To me it is just a way of writing more unneeded code since `public string Name` does the exact same as `public string Name {get;set;}` (apart from creating some private variable that is 100% public available anyway using the `Name` attribute). Also why shouldn't I expose public fields? It's written a lot of places but no one writes why – CutePoison Oct 03 '22 at 05:43
  • @RandRandom No, still the same. Just an explanation of what it does, and not *why* we should use it isntead of just making `Name` public – CutePoison Oct 03 '22 at 05:43
  • did you read the first answer? why? cause of interface. why? cause of validating the value in setter. why? cause extending logic without breaking serialization. why? cause databinding mechanism ignore fields, so impossible without a property. – Rand Random Oct 03 '22 at 05:48
  • Yes, I read it. *validating the setter*; if you try set `Person.Name=10` then it won't compile anyway. Can you mention one problem using `public string Name {get;set;}` solves? Not just "we won't expose fields" but an actually thing that it does that just having `public string Name` can't do? I know we can change `get`/`set` to do stuff when we use them (e.g to validate some data first), but that is not my concern. I'm talking about the raw `{get;set;}` not anything else where they call some validtaion functions first – CutePoison Oct 03 '22 at 05:55
  • `Person.Name=10` is not an example of validation in the setter. That's a static typing check compiler error. Validation might be passing an empty string as a name, or a string that is too long, and rejecting it in these cases. – ProgrammingLlama Oct 03 '22 at 06:48
  • Yes, but we are outside the `{get;set;}` part. Then we have written a validaiton function for `set` and that is not what my question is about. Please see the editted question for clarification – CutePoison Oct 03 '22 at 06:50
  • I don't get how you refuse to take the answers that people provide, it is exactly what you're asking for, yes, we know that calling the `Name` property or a public `_name` field is the same in terms of the end result value, but no, these are fundamentally different things when you look at the compiled output, using properties(or get/set methods in general) provide a layer of encapsulation, and ease of data processing, thus it is never the same as simply calling a field value, the field is hidden, not visible from the outside, you can't access it from outside due to its protection level – A Sad Shoe Oct 03 '22 at 07:26
  • As written, I get that it isn't the *same thing* but I'm asking for different use cases. The very simple question *why* would you use the`{get;set;}` instead of just the public field - just one simple example where it is an advantage of using the raw `{get;set;}` (not a `set` where we validate data etc, but only the raw `set`). I don't care about that the `get/set` creates "GetName()", "SetName()" functions etc. in the background, or that it creates some private variable or some other stuff. I'm talking *only* about the one and only `Name` field and how to access that field. – CutePoison Oct 03 '22 at 07:37
  • you can't ask for a reason as to why you should use A instead of B, then say you don't care that there's a reason, then why ask a question at all, the reason is encapsulation, if you don't want to do encapsulation, and you don't care about any validation or simplified get/set logic, then sure, don't use it, but don't get why you ask then. – A Sad Shoe Oct 03 '22 at 07:45
  • gave you examples you simply refuse to take them in… how many use cases do you need to satisfy your question? – Rand Random Oct 03 '22 at 07:45
  • A 'use case' for you, might be if you were to have a 'Name' field/property, but also want 'Firstname' for display purposes, then a property makes a decent amount of sense, as you can define a get only property with a lambda of `=> Name.Split(' ')[0]`, which would output the result before the first space, but can be called as a field/property, eg. Console.WriteLine(obj.Firstname), rather than having to allocate a field to the value or making a `GetFirstname(string name)` method – A Sad Shoe Oct 03 '22 at 07:48
  • this doesn't really have much of an actual impact, other than being prettier when it comes to displaying the firstname in code, but that's about the only sort of 'functionality' that you'll get if you ignore encapsulation, data processing. – A Sad Shoe Oct 03 '22 at 07:50

0 Answers0