728

I am learning ASP.NET MVC and I can read English documents, but I don't really understand what is happening in this code:

public class Genre
{
    public string Name { get; set; }
}

What does this mean: { get; set; }?

a3y3
  • 1,025
  • 2
  • 10
  • 34
tree em
  • 20,379
  • 30
  • 92
  • 130
  • 12
    In general remember--setters make your object mutable, a bad idea. getters violate "Tell an object what to do, don't ask it for information and manipulate it yourself". So in general, don't add setters and getters by default. You will need them, often, but you should always find a real need before you add them. In particular setters should almost never be used in production code (Strive for immutability wherever possible, and when mutation is needed you should ask it to mutate for you, not set a value). – Bill K Apr 02 '15 at 22:07
  • 16
    Just to add something... If you don't put `{get; set;}` you are creating a **Field** but if you put the `{get; set;}` you are creating a **Property**. Having a property could make some things easier especially when working with Reflection. – Seichi May 04 '15 at 21:40
  • 2
    @Seichi using a get-setter creates a Field too, but this one is hidden, declared as private and modified by the auto created properties; all of that made by the compiler. – Jonathan Ramos May 07 '17 at 23:12
  • 2
    aren't auto properties defeat the purpose of *private* fields? – mireazma Jan 22 '18 at 09:28

21 Answers21

695

It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):

private string name;
public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • 126
    Klaus, can you explain what will happen with this code? It could benefit from a more thorough explanation. – TylerH Nov 17 '14 at 18:53
  • 3
    So, just to be sure: it is like if I overloaded the `=` operator, but only for one particular element, right? – Hi-Angel Jan 12 '15 at 09:01
  • 10
    Why do we need the private var. :-/ shame. – Oliver Dixon May 29 '16 at 11:57
  • 3
    @TylerH The reason for the private variable is encapsulation, the get/set provides a "gate" to get or set the variable. Although there are many reasons not to use get/setters because the "gate" can break the encapsulation of the private variable. (it shouldn't be accessible) – Alexander Mar 09 '17 at 08:47
  • 2
    Can you also use just `public string name;` or is it bad practice to make properties public? – E.V.I.L. Aug 29 '17 at 17:40
  • @MadTomVane `public string name` is a field in this context, not a property, and making it public defeats the purpose of using a property. I.e. a property provides a safer way to access `name`. Why shouldn't we use public fields? Because they break encapsulation. – arkon Sep 12 '17 at 06:32
  • @OliverDixon Do you really want the compiler naming your variables for you? – arkon Sep 12 '17 at 06:33
  • 2
    so `value` is a reserved keyword and automatically filled by the call? so I would say `Name = "blah"` and `value` takes on "blah", which then gets assigned to the private `name`? How does typechecking work? – mpag Oct 20 '17 at 17:37
  • 1
    I too want to know where `value` comes from. If it's coming from where I think it's coming from, then it seems to me like a poor design choice for the language. – davidtgq Dec 18 '17 at 23:15
  • 4
    @mpag & dtgq 'value' is an implicit argument, see [MS Using Properties](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties#the-set-accessor). Simple, not poor design choice. Typechecking is preserved – stefano Sep 23 '18 at 17:00
  • 8
    It may be obvious, but I want to clarify that the shorthand is not *literally* a shorthand for that. That is, no private variable `name` is created. If you tried to reference this private variable within the class, it will fail. I'm not sure how C# does it, but it behaves as if there is a private variable with no name, which you cannot access in your code. – Denziloe Feb 09 '19 at 18:51
  • Consider this answer: [Naming convention - underscore in C++ and C# variables](https://stackoverflow.com/a/3136618/7389293) – carloswm85 Jul 28 '21 at 14:14
531

So as I understand it { get; set; } is an "auto property" which just like @Klaus and @Brandon said is shorthand for writing a property with a "backing field." So in this case:

public class Genre
{
    private string name; // This is the backing field
    public string Name   // This is your property
    {
        get => name;
        set => name = value;
    }
}

However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.

get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).

There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.

Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
                        //called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();

//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)

Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.

public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now 

We can set the name of 'g1' to Hip Hop by writing the following

g1.Name = "Hip Hop";

What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property

set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:

public class g1 //We've created an instance of the Genre Class called "g1"
{
    private string name;
    public string Name
    {
        get => name;
        set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because 
                              //'value' in 'g1' was set to "Hip Hop" by previously
                              //writing 'g1.Name = "Hip Hop"'
    }
}

It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.

So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing

console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property 
                             //and returns the field 'name' which we just set to
                             //"Hip Hop"

and if we ran this we would get "Hip Hop" in our console.

So for the purpose of this explanation I'll complete the example with outputs as well

using System;
public class Genre
{
    public string Name { get; set; }
}

public class MainClass
{
    public static void Main()
    {
        Genre g1 = new Genre();
        Genre g2 = new Genre();
        Genre g3 = new Genre();

        g1.Name = "Hip Hop";
        g2.Name = "Rock";
        g3.Name = "Country";

        Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);
    }
}

Output:

"Genres: Hip Hop, Rock, Country"
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Josie Thompson
  • 5,608
  • 1
  • 13
  • 24
  • 22
    Personally i would just comment it out as such `set{name = value;} // 'value' here is equal to "Hip Hop"` – maraaaaaaaa Sep 04 '15 at 17:18
  • Can you explain why we even need the backing field? – Oliver Dixon May 29 '16 at 11:58
  • 2
    @iLoveUnicorns, it's there for the purpose of [data abstraction](https://en.wikipedia.org/wiki/Abstraction_(software_engineering)). The backing field is what contains the actual data. The property definition actually defines how the data is accessed with the `get` and `set` methods. The link I provided has an excellent quote from John Guttag at the top of the page. I would recommend reading his book or even take [this free online course](http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/) – Josie Thompson Jun 03 '16 at 01:34
  • 1
    Thanks for the explanation. But, what's the motive behind behind creating a private variable and making it read/write as a public variable? Instead, why wouldn't you make the variable public from the beginning? – kovac Aug 15 '16 at 07:39
  • @Sadeep Well, in a way it is public from the beginning. A property needs a backing field to reference in order to function correctly. The private variable is the backing field. If you try [to reference the property itself](http://stackoverflow.com/questions/3272889/properties-backing-field-what-is-it-good-for) you'll fall into infinite recursion. – Josie Thompson Aug 16 '16 at 16:26
  • 7
    Can't we just use: `public class Genre{public string Name;}` instead of : `public class Genre{ public string Name { get; set; }}`. I mean, Why do we even need { get; set; }? – user2048204 Nov 07 '16 at 17:24
  • It sounds like accessors can only work on private fields. That's not true. Accessors are just syntactical sugar for methods. For example, you can write a getter that calculates a value **on demand** without ever using a backing field. – adjan Oct 18 '18 at 15:05
  • 3
    Seems like my concern has already been echoed. If you declare this way: "public string Name { get; set; }" and you access this way: g1.Name = "Hip Hop"; - then where is the Object Orientation? I don't even need the so-called "backing field". The backing field doesn't even exist, as far as I am concerned. Because I only access the public field. And if the public field is "public" then it is not OO compliant. Let's all go back to COBOL. – Baruch Atta Apr 29 '19 at 12:21
  • "Encapsulation" is the word that I was looking for. If you make Name "public", then where is the encapsulation? Anyway, just tell me the correct syntax, and I am good. What is the proper syntax if you make Name static? – Baruch Atta Apr 29 '19 at 12:36
  • 4
    Great answer, but if we are being pedantic, “set” is a mutator, not an accessor. – pythlang May 17 '19 at 00:24
  • 1
    @pythlang why's `set` defined as _accessor_ here?: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/set – Det Aug 24 '19 at 16:36
  • 1
    @Det I think there's some semantic disagreement on what constitutes an accessor. It looks like Microsoft defines an accessor as anything which accesses private data, even if it mutates the data as well. While pythlang defines an accessor as something which just accesses private data without mutating it. I've think I've seen other big-name computer scientists define accessors this way as well. At the end of the day, I don't think it makes too much of a difference. – Josie Thompson Aug 24 '19 at 18:28
  • @Det Easy: "KISS". Notice: "pedantic". I disagree with them in this case; I do understand their rationale in doing so _(i.e. pedantic)_. Invoking _accessor_ nomenclature as a catch-all ignores the entire set of _mutator_ functions that exist, somehow implying that they are identical in operation to that of an _accessor's_. In application, an _accessor_ does not fundamentally operate based on the same design pattern of that which is associated with _mutation_. I digress... – pythlang Oct 05 '19 at 20:02
  • If it's anything like C++, you need the `()` because you need the class, whereas `Genre` is just the type of that class. It also resembles function-call syntax because it is that--its calling the constrictor for `Genre` (it has no name). It is this constrictor that instantiates a new object of type `Genre` and returns it so that it can be assigned to your `g1` variable. Hopefully this isn't far off. I'm a complete C# noob, and it's been a while since I used C++ anyways. Though in C++ I'm fairly certain you can skip the `()` and it will automatically call the hidden, default constrictor . . . – RastaJedi Jul 06 '20 at 19:52
  • . . . Which also would be called if you used the parenthesis but didn't define a constrictor. Hopefully this helps, and forgive me if this is a bit incorrect. – RastaJedi Jul 06 '20 at 19:54
  • Hey newbie here. I have a question to @Josie. In your last example you created Name method with public access modifier, but wouldn't it be the same thing if you just have created public Name variable as `public string Name` instead of creating Name method with getters and setters? Because you did not use any private variable to be encapsulated, was it intended? – Elif May 16 '21 at 11:50
  • @Elif it's been quite a while since I've written any C#, but if I remember correctly the last example is "syntactic sugar" for the first example - meaning that C# is doing the stuff in the first example under the hood. – Josie Thompson Jan 22 '22 at 20:52
111

Those are automatic properties

Basically another way of writing a property with a backing field.

public class Genre
{
    private string _name;

    public string Name 
    { 
      get => _name;
      set => _name = value;
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Brandon
  • 68,708
  • 30
  • 194
  • 223
  • 10
    What is called " backing field"? – tree em Feb 23 '11 at 20:54
  • 5
    @stackunderflow: The backing field is where the data is stored. (what is returned when using `get`, and persisted using `set`). Like the cupboard to which `get` and `set` opens the door of. – Grant Thomas Feb 23 '11 at 20:57
  • 6
    @stackunderflow: In this answer, the backing field is `_name`. In the automatic property, the backing field is hidden. – Justin Feb 23 '11 at 21:00
38

This is the short way of doing this:

public class Genre
{
    private string _name;

    public string Name
    {
      get => _name;
      set => _name = value;
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
froeschli
  • 2,692
  • 2
  • 28
  • 55
38

It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.

You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.

Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • 2
    Kelsey - could you explain how this syntax makes it any more "flexible" code? I don't see it. If you would add any "logic" to the setter or getter, then in ether case (with or without private data) you would still break the interface, as it is, and need some coding. – Baruch Atta Apr 29 '19 at 12:33
  • @BaruchAtta: changing an auto property to a non auto property or vice-versa does not break the interface. An interface says that there WILL be a getter or setter property, not how that is implemented. In fact, without looking at the code, the only way to tell the difference is by looking at the generated IL and seeing that one has a weird name and one doesn't (and in other CLI languages even that may not be true, and it's not part of the C# spec so a future or forked version doesn't have to do that). – jmoreno Nov 25 '21 at 16:02
32

Basically, it's a shortcut of:

class Genre{
    private string genre;
    public string getGenre() {
        return this.genre;
    }
    public void setGenre(string theGenre) {
        this.genre = theGenre;
    }
}
//In Main method
genre g1 = new Genre();
g1.setGenre("Female");
g1.getGenre(); //Female
learnAsWeGo
  • 2,252
  • 2
  • 13
  • 19
Jirson Tavera
  • 1,303
  • 14
  • 18
  • 5
    This doesn't answer the question. The OP was talking about properties. – theB Sep 12 '15 at 01:16
  • 8
    i know the properties Get and Set, it's an example that help understand better – Jirson Tavera Sep 15 '15 at 13:51
  • 3
    @theB in fact, OP is asking about the meaning of `{ get; set; }`, so this answer, I think, is a good one for those who come from other programming languages. – carloswm85 Jul 27 '21 at 17:55
15

Basically it helps to protect your data. Consider this example without setters and getter and the same one with them.

Without setters and getters

Class Student

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstProject
{
    class Student
    {
        public string name;
        public string gender;
        public Student(string cName, string cGender)
        {
            name = cName;
            gender= cGender;
        }

     }
}

In Main

 Student s = new Student("Some name", "Superman"); //Gender is superman, It works but it is meaningless
 Console.WriteLine(s.Gender);

With setters and getters

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstProject
{
    class Student
    {
        public string name;
        private string gender;
        public Student(string cName, string cGender)
        {
            name = cName;
            Gender = cGender;
        }

        public string Gender
        {
            get { return gender; }
            set
            {
                if (value == "Male" || value == "Female" || value == "Other")
                {
                    gender = value;
                }
                else
                {
                    throw new ArgumentException("Invalid value supplied");
                }
            }
        }
    }
}

In Main:

  Student s = new Student("somename", "Other"); // Here you can set only those three values otherwise it throws ArgumentException.
Console.WriteLine(s.Gender);
Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54
  • 3
    I'm new at C#, but I think that this one is a good explanation. – carloswm85 Jul 28 '21 at 13:16
  • what is "value" in your example? Thanks – Dory Nguyen Jan 07 '22 at 10:41
  • @DoryNguyen: It seems "value" is the implicit argument of the set function. So if I call myObject.Property = 875, the set function will have 875 assigned to the variable "value". You just have to know that's the syntax. Similarly, "get" expects you to return a value of the appropriate type. – MichaelS Jan 28 '22 at 05:41
  • 1
    Nice explanation, but what is `Name { get; set; }` – john k Mar 12 '23 at 15:35
10

Its an auto-implemented property for C#.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
9
  • The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property.

  • A property can have a 'get' accessor only, which is done in order to make that property read-only

  • When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore. this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.

Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
6

They are the accessors for the public property Name.

You would use them to get/set the value of that property in an instance of Genre.

TimCodes.NET
  • 4,601
  • 1
  • 25
  • 36
6

That is an Auto-Implemented Property. It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.

You can read more on MSDN's Auto-Implemented Properties Programming Guide.

Dusda
  • 3,347
  • 5
  • 37
  • 58
5

In the Visual Studio, if you define a property X in a class and you want to use this class only as a type, after building your project you will get a warning that says "Field X is never assigned to, and will always has its default value".

By adding a { get; set; } to X property, you will not get this warning.

In addition in Visual Studio 2013 and upper versions, by adding { get; set; } you are able to see all references to that property.

enter image description here

Omid Ebrahimi
  • 1,150
  • 2
  • 20
  • 38
5

This mean that if you create a variable of type Genre, you will be able to access the variable as a property

Genre oG = new Genre();
oG.Name = "Test";
abatishchev
  • 98,240
  • 88
  • 296
  • 433
David Brunelle
  • 6,528
  • 11
  • 64
  • 104
  • 5
    When you don't use auto-implemented properties, you still able to access it in this manner. i.e. AIP is not about access from outside, but about declaration inside a class. – abatishchev Feb 23 '11 at 21:02
5

Its basically a shorthand. You can write public string Name { get; set; } like in many examples, but you can also write it:

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value ; } // value is a special keyword here
}

Why it is used? It can be used to filter access to a property, for example you don't want names to include numbers.

Let me give you an example:

private class Person {
    private int _age;  // Person._age = 25; will throw an error
    public int Age{
        get { return _age; }  // example: Console.WriteLine(Person.Age);
        set { 
            if ( value >= 0) {
                _age = value; }  // valid example: Person.Age = 25;
        }
    }
}

Officially its called Auto-Implemented Properties and its good habit to read the (programming guide). I would also recommend tutorial video C# Properties: Why use "get" and "set".

toobladink
  • 54
  • 5
Randel
  • 421
  • 6
  • 11
4

Such { get; set; } syntax is called automatic properties, C# 3.0 syntax

You must use Visual C# 2008 / csc v3.5 or above to compile. But you can compile output that targets as low as .NET Framework 2.0 (no runtime or classes required to support this feature).

linquize
  • 19,828
  • 10
  • 59
  • 83
2

Get set are access modifiers to property. Get reads the property field. Set sets the property value. Get is like Read-only access. Set is like Write-only access. To use the property as read write both get and set must be used.

Ashraf Sada
  • 4,527
  • 2
  • 44
  • 48
  • 1
    i think get set are not access modifiers, infact they are accessors. Access modifiers are like : public, private, internal etc. – Rohit Arora Nov 17 '15 at 09:45
2

Get is invoked when the property appears on the right-hand side (RHS) Set is invoked when the property appears on the left-hand side (LHS) of '=' symbol

For an auto-implemented property, the backing field works behind the scene and not visible.

Example:

public string Log { get; set; }

Whereas for a non auto-implemented property the backing field is upfront, visible as a private scoped variable.

Example:

private string log;

public string Log
{
    get => log;
    set => log = value;
}

Also, it is worth noted here is the 'getter' and 'setter' can use the different 'backing field'

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Bala
  • 45
  • 6
  • This does not seem to answer the question asked. – TylerH May 24 '17 at 22:37
  • Provided hint on when the get & set is invoked. All the answers mentioned above, makes an impression that the backing field for get & set is the same. But it is not the case. So my answer is very much relevant to the main question. Hope you agree with me. – Bala May 30 '17 at 16:58
  • 1
    For an auto-generated property, which is what the question asks about, there can't be different backing fields used for the getter and the setter; there is only one backing field. For a non-auto property (which the question doesn't ask about) there may not even conceptually be a backing field at all. Additionally, you can write a program with a getter on the left hand side of an assignment operator and one with a setter on the right hand side of an assignment operator. So not only is all of this information not answering the question asked, but it's all also wrong. – Servy May 30 '17 at 17:00
2

A property is a like a layer that separates the private variable from other members of a class. From outside world it feels like a property is just a field, a property can be accessed using .Property

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName => $"{FirstName} {LastName}";
}

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName { get { return $"{FirstName} {LastName}"; } }
}

FullName is a Property. The one with arrow is a shortcut. From outside world, we can access FullName like this:

var person = new Person();
Console.WriteLine(person.FullName);

Callers do not care about how you implemented the FullName. But inside the class you can change FullName whatever you want.

Check out Microsoft Documentation for more detailed explanation:

https://learn.microsoft.com/en-us/dotnet/csharp/properties

MING WU
  • 2,962
  • 1
  • 12
  • 16
0

Define the Private variables

Inside the Constructor and load the data

I have created Constant and load the data from constant to Selected List class.

public  class GridModel
{
    private IEnumerable<SelectList> selectList;
    private IEnumerable<SelectList> Roles;

    public GridModel()
    {
        selectList = from PageSizes e in Enum.GetValues(typeof(PageSizes))
                       select( new SelectList()
                       {
                           Id = (int)e,
                           Name = e.ToString()
                       });

        Roles= from Userroles e in Enum.GetValues(typeof(Userroles))
               select (new SelectList()
               {
                   Id = (int)e,
                   Name = e.ToString()
               });
    }

  public IEnumerable<SelectList> Pagesizelist { get { return this.selectList; } set { this.selectList = value; } } 
  public IEnumerable<SelectList> RoleList { get { return this.Roles; } set { this.Roles = value; } }
  public IEnumerable<SelectList> StatusList { get; set; }

}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Hari Lakkakula
  • 199
  • 1
  • 4
0

Properties are functions that are used to encapsulate data, and allow additional code to be executed every time a value is retrieved or modified.

C# unlike C++, VB.Net or Objective-C doesn’t have a single keyword for declaring properties, instead it uses two keywords (get/set) to give a much abbreviated syntax for declaring the functions.

But it is quite common to have properties, not because you want to run additional code when data is retrieved or modified, but because either you MIGHT want to do so in the future or there is a contract saying this value has to be a exposed as a property (C# does not allow exposing data as fields via interfaces). Which means that even the abbreviated syntax for the functions is more verbose than needed. Realizing this, the language designers decided to shorten the syntax even further for this typical use case, and added “auto” properties that don’t require anything more than the bare minimum, to wit, the enclosing braces, and either of the two keywords (separated by a semicolon when using both).

In VB.Net, the syntax for these “auto” properties is the same length as in c# —- Property X as String vs string X {get; set;}, 20 characters in both cases. It achieves such succinctness because it actually requires 3 keyword under the normal case, and in the case of auto properties can do without 2 of them.

Removing any more from either, and either a new keyword would have had to be added, or significance attached to symbols or white space.

jmoreno
  • 12,752
  • 4
  • 60
  • 91
0

You can use the setter to trigger an event every time the property changes. This is useful in Unity.

Instead of using a dedicated method like MyClass.UpdateAccess(Role.Registered)

public void UpdateAccess(Role role)
{
   userRole = role;
   EventsManager.Instance.UpdateUI();
}

You can write MyClass.UserRole = Role.Registered

private Role userRole;
public Role UserRole
{
   get { return userRole; }
   set
   {
     userRole = value;
     //Maybe have a switch here to decide what to do depending on the value...
     EventsManager.Instance.UpdateUI();
   }
}
Ando
  • 1,802
  • 4
  • 25
  • 47