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);
}
}
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.
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.
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.
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
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; }
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.
来源:https://stackoverflow.com/questions/17186432/what-is-the-advantage-of-using-private-variables-in-c-sharp