0

why to use accessors in c#.net while we can use simple assignment like

  public string name = "Haymen";

instead of doing this:

 public string Name 
{
  get 
{ 
  return name; 
}
set 
{
   name = value; 
}
}

and how this property gonna set or return something since it don't have any way to set anything apparently ?

    public class Movie 
    {
      public int ID { get; set; }
    }
user3111824
  • 173
  • 2
  • 4
  • 11

3 Answers3

0

Skeet has » an article about just that! Your case is covered by automatic properties, so you don't have all the writing work.

LueTm
  • 2,366
  • 21
  • 31
0

It depends on what your trying to do, you use accessors for a variety of reasons, one of which is to ensure that class properties are kept private and can only be directly manipulated internally.

An example :-

private int _myAge {get; set;}

public int MyAge
{
   get
   {      
      if(_myAge == null)
      {
         _myAge == GetMyAge();
      }

      return _myAge; 

   }

}
Derek
  • 8,300
  • 12
  • 56
  • 88
-1

Use

public string name = "Haymen";
  1. If you know for sure you will never need to debug the access to that variable (i.e. set a breakpoint when somebody reads/writes it).
  2. If you know changing it will never effect the internal state of your object (i.e. side effect that you depend on or expect).
  3. You want to have less lines to look at and you have met the above.
  4. You want a "data only class" for XML Serialization and you don't want to create a lot of code to do the conversion for private methods (at least as of C# 3.5).

NOTE That being said, in general, you should not be exposing fields as public members. See here.

FuzzyBunnySlippers
  • 3,387
  • 2
  • 18
  • 28