8

Sample code (alternative code is below),

// person.cs
using System;
class Person
{
    private string myName ="N/A";

    // Declare a Name property of type string:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        {
           myName = value; 
        }
    }
    public override string ToString()
    {
        return "Name = " + Name;
    }

    public static void Main()
    {
        Person person = new Person();
        Console.WriteLine("Person details - {0}", person);
        person.Name = "Joe";
        Console.WriteLine("Person details - {0}", person);

    }
}

Can't we directly write, changing myName from private to public, no requirement to declare another public variable Name and no need to use get and set?

alternative code

    // person.cs
    using System;
    class Person
    {

        public string myName ="N/A";

        public override string ToString()
        {
            return "Name = " + myName;
        }

        public static void Main()
        {
            Person person = new Person();
            Console.WriteLine("Person details - {0}", person);
            person.myName = "Joe";
            Console.WriteLine("Person details - {0}", person);

        }
    }
Sam
  • 6,961
  • 15
  • 44
  • 63
michael
  • 637
  • 1
  • 6
  • 15
  • 1
    possible duplicate of [Difference between Property and Field in C# 3.0+](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0) – ken2k Jun 19 '13 at 08:34

6 Answers6

16

Externally visible properties are better than fields because:

  • Properties allow better encapsulation. Fields are a fixed implementation and allow direct access from consumers. Properties:

    • are loosely coupled (since underlying field can change from variable to database anytime)

    • allow custom logic (validation, event notification, lazy loading, etc.)

    • control access (since logic can be built in get/set, even declared read-only or write-only).

  • Fields cannot be used in interfaces. This is an impediment to Test Driven Development (interface first).

  • Automatic or Auto-Implemented Properties are as easy to declare as fields and also optimized to perform on par with fields. See here.

  • Declaring an externally visible field (public, protected, protected internal) is a FxCop violation. See rule CA1051.

  • Changing a field to a property is a breaking change, since the calling code needs to be recompiled (applies to binary serialization as well).

  • Properties are recognized by many libraries in .NET for tasks such as XML serialization, WPF bindings, ASP.NET 2-way binding, etc. and also by Visual Studio designer.

Channs
  • 2,031
  • 1
  • 14
  • 18
  • 1
    You can also do extra things on the get/set of a property if you need to (such as `INotifyPropertyChanged` and lazy loading sub values). – Pondidum Jun 19 '13 at 08:42
  • @Pondidum +1, I have updated my answer with your inputs. Thanks! – Channs Jun 19 '13 at 08:51
  • @Blau +1, removed that point. This understanding was from an older conversation at work, however, I disproved myself with a small piece of code. Will try digging up the correct context. Thanks! – Channs Jun 19 '13 at 09:38
10

You are cracking up one of the bases of OOP -> information hiding / encapsulation

By defining your properties as public you give EVERYONE access to them and they can be changed (corrupted) as desired. This way you cannot promise that your objects will be in a consistent state all of the time.

From Wikipedia

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination[1][2] thereof:
- A language mechanism for restricting access to some of the object's components.[3][4]
- A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.[5][6]

Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of object oriented programming, while other programming languages which provide lexical closures view encapsulation as a feature of the language orthogonal to object orientation.

The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition.

bash.d
  • 12,357
  • 2
  • 24
  • 37
  • In the above examples, in both cases changes can be made as shown below: person.Name = "Robert"; (1st example) or as person.myName = "Robert"; (2nd example) what is the advantage and how is it protected by using private. Please elaborate more – michael Jun 19 '13 at 08:34
  • I agree, however, in the OP the public property `Name` has a setter. So, this also allows for mutating the data. – Davin Tryon Jun 19 '13 at 08:34
  • Yes, but this is a feature of the language. It gives you the possibility to check the set value. But if you consider pure C++ there are no such Features to support controlled setting. – bash.d Jun 19 '13 at 08:36
  • Also avoiding clutter, if a class has 10 private properties to do something, but you only need to call the one thing, you don't want 10 properties distracting you. Also it promotes better design, having access to every property seduces you to use them to alter the behavior 'a little bit'. But generally the program is better understood if those things are done inside the class holding the property. – MrFox Jun 19 '13 at 08:37
0

In your example there is actually no difference between these 2 approaches. Generally, properties gives you a possibility to make them readonly for other classes (with private setter) - you won't be able to do such thing with the field. Public fields/property setters broke the encapsulation rule of OOP.

tdragon
  • 3,009
  • 1
  • 14
  • 17
0

In OOP the convention is to hide all your variables from users and use Getters and Setters instead to manipulate with them. There are cases when you will be needing to change variables value until it is saved. For example you prompt user to enter some value that will be velocity and users enter the value in MPH but you want to convert them and store as Km/h or m/s. Now in this case having setter makes sense. There are also cases when you want setter or getter to be private for variable to be read only or write only. But To sum up In OOP Convention is to use setters and getters instead of public variables. This is the part of Encapsulation Concept

Dimitri
  • 2,671
  • 6
  • 32
  • 56
0

You can do, but its not good pratcie. Encapusalting the private varaible as a property means you have greater control in restricting what clients can and can't do

If its seems a little verbose you can also use the following

public string Name { get; set; }
beaumondo
  • 4,359
  • 7
  • 26
  • 39
  • 1
    Note that this is called *auto-implemented properties* and is available since C# 3.0. More importantly, it allows you to add logic to the getter or setter later should you want to do so, without introducing a breaking change. – user Jun 19 '13 at 12:20
0

As bash.d wrote this are bases of OOP.

In this Case i would recommend to put the Name in the Constructor:

 class Person
 {

    public Person(string name)
    {
       this.myName = name;
    }

    private string myName ="N/A";
    public string Name
    {
        get 
        {
           return myName; 
        }
        private set 
        {
           myName = value; 
        }
    }

    public override string ToString()
    {
        return "Name = " + Name;
    }

    public static void Main()
    {
        Person person = new Person("Joe");
        Console.WriteLine("Person details - {0}", person);
        Console.WriteLine("Person details - {0}", person);

    }
 }

Other ways use an Method to Set the Value, were you can check the handled object.

Smartis
  • 4,669
  • 3
  • 29
  • 44