This question already has answers here:
OO Design - do you use public properties or private fields internally? [duplicate]
(10 answers)
Closed 9 years ago.
class Student
{
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value; // Possible logical checks may be implemented here in the future
}
}
public Student (firstName)
{
this.firstName = firstName; // Option 1
// Or
FirstName = firstName; // Option 2
}
}
which of the two lines is more standard?
do we use the private or the public members in the constructor?
You could go with option 3
public string FirstName {get; set;}
public Student (firstName)
{
FirstName = firstName;
}
It depends... Often on things not included in your example. For one thing, your entire property can be shortened to an auto-implemented property:
public string FirstName { get; set; }
Which would make the question moot in this case. Beyond that, the question comes down to what sort of logic may exist (now or in the future) in the property and whether or not that logic needs to be invoked by the constructor.
For example, does the property internally check for a required value or perform some other validation? Something like this:
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException("FirstName");
firstName = value;
}
}
In a case like this clearly you'd want the constructor to use the property and not the backing field so that the logic is applied when constructing the object.
Conversely, you might have logic that should only be used when accessing the setter but not when constructing the object. Off the top of my head one example might be an object which maintains information about a Location. It might have an Address property and a Coordinates property, and any time one of them changes there is a back-end process to geolocate the new value and update the other. But you might have a constructor which accepts both (perhaps when re-building an existing Location from a database) and it wouldn't make sense to perform the geolocation during construction. In that case you'd set the backing fields and not the properties.
For lack of a compelling reason not to use the properties, I'd generally prefer to use them instead of the backing fields. Simply because logic might be added to those properties later that all accessors should use. I also find it more likely that the properties have a more meaningful name than backing fields (for example, FirstName is more readable/meaningful than _firstName) so the preference would be to keep the rest of the code as readable as possible and to prefer more readable names.
It is a stylistic choice that doesn't really matter. Personally, I use the public property name, because I like to use auto properties, and that is the only option in that case. Using the public property keeps my code consistent.
When I am writing POCOs (Plain Old CLR Objects) where things are trivial, I go with this approach:
public class POCO
{
public POCO()
{
Name = "Moo-Juice";
}
public string Name { get; set; }
}
In non-trivial cases where I actually need the member variable, I prefix it with _ (this helps in intellisense, believe me - and allows you to distinguish between members and locals):
public class NonTrivial
{
private string _name;
public NonTrivial()
{
_name = "Jon Skeet"; // He is non-trivial
}
}
This way I avoid polluting my code with this. everywhere.
It depends:
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = (value=="mycheck")?"default":value;
}
}
If your property has some validations then you should go for:
public Student (firstName)
{
FirstName = firstName;
}
The most common is to use the property, but it is a matter of choice.
In this case particularly, you should use automatic property:
public string FirstName { get; set; }
And the compiler adds the backing field automatically.
You can also choose to not add the parameter constructor, as since C# 3.5 (IIRC), you can use automatic initializers:
new Studant() { FirstName = "John Doe" }
Which calls the constructor, and sets the property in one line.
Overall, I tend to only request a constructor parameter for things it really depend on (see: dependency injection), and let the not always needed ones optional until they are required, like validating before persisting.
Related
I'm going to build my MVC Web Application and I created my data models.
I found online many ways to compile a data model code. This is easiest one, using only public properties:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
But I also found a version using a private variable and a public properies, like this:
public class Person
{
private int id;
private string firstName;
private string lastName;
public int Id { get { return id; } set { id = value; } }
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
}
What is the difference between these two data models?
When is more advisable using the first one or the second one?
This is the same like asking: what is a difference bwteen auto properties and normal properties.
Auto properties:
easy creation (less to type)
internal field is generated for you automatically by compiler
Not possible to debug (set a break point inside the property)
Normal properties
Sligtly more code to type
Easy to debug
More code can be injected inside get and set
If first example compiler will create private field for every automatic property itself, but they behave exactly the same. More info on MSDN
I would suggest second approach as you have more control how property works, but there is nothing wrong in using first one.
The fiest block you have are auto-properties, and under the hood the c# will be compiled similar to the second block, so in this case there is no difference. Take a look at these posts here:
C# 3.0 auto-properties - useful or not?
What are Automatic Properties in C# and what is their purpose?
Any reason to use auto-implemented properties over manual implemented properties?
If you were implementing the INotifyPropertyChanged interface, then you would need to use the traditional way as you would be interacting with the property in the setter, see example...
http://msdn.microsoft.com/en-us/library/ms743695.aspx
New to C#, and I understand that encapsulation is just a way of "protecting data". But I am still unclear. I thought that the point of get and set accessors were to add tests within those methods to check to see if parameters meet certain criteria, before allowing an external function to get and set anything, like this:
private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.
private string myName = "mary";// the backing field.
public string MyName // this is a property, which sets/gets the backing field.
{
get
{
return myName;
}
set
{
if (value != "Silly Woman"){
myName = value;
}
}
}
But I've been seeing code in c# which just looks like this:
public string MyName { get; set; }
Why would you just have a get and set with nothing in there, - isn't that the same as just declaring your private backing field public? If you can just get and set it from outside, why wouldn't you just do it directly?
Indeed, creating an auto-property as follows:
public string Name { get; set; }
is identical to building a property backed by a field:
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:
public string Name {
get { return _name; }
set { if (value == null) throw new Exception("GTFO!"); _name = value; }
}
Another thing is, you can make properties virtual:
public virtual string Name { get; set; }
which, if overridden, can provide different results and behaviours in a derived class.
By using public string MyName { get; set; }, you leave an ability to change its logic later without the need to recompile/change other code that uses your property.
For example, if you are making a library and v1 uses a field and v2 uses a property, applications that work with v1 will not work with v2 without recompilation (and, potentially, code changes if they are written in some .NET language that has different syntax for accessing fields).
Another important difference is in serialization scenarios -- a lot of them do not support fields. Also any interface that requires a property can not be implemented without using one, but depending on interface it may not be required to do any additional checks/logic in it.
It makes it easier to add logic later. If you have a class that has a public field that you want to change to a property, you have to recompile everything that uses your class. That's a key point that I didn't understand initially.
If you have a class:
public class MyClass
{
public string MyString;
}
You could access the value like this:
var myClass = new MyClass();
string s = myClass.MyString;
Now change that to a property:
public class MyClass
{
public string MyString { get; set; }
}
How is it accessed? The exact same way:
var myClass = new MyClass();
string s = myClass.MyString;
So no big deal, right? Well, actually....
Properties are actually compiled into getter and setter methods:
get_MyString() and set_MyString(string value)
So the two methods do produce different compiled code. Now if all your code that uses this class is in the same project, is not as big a deal, because it will all be compiled together. But if you have an API library that you've distributed, it can be a much bigger deal to update.
Because it is easier to change the Code if you want to add the checks/tests later on.
Especially if you have many inheritance and many classes in your code it is very hard to change the implementation from a public variable to a public Property.
Moreover you can add to the get and set within the property different attributes, e.g. if you are using reflection. The get and set of the property are internally different methods. If you have just a public variable /field it is not possible to added different properties to the different access ways.
Yeah, but you can easily change it to:
public string MyName { get; private set; }
Plus, properties are used in other scenarios, like DataContracts and Serialization... so, this is a nice feature... (Mostly, syntactic sugar. I think) EDIT: I take that back.. you can apply virtual to it, so it's not the same
I'm a newbie and I'm trying to learn the basics of C#. This might sound quite trivial and may be stupid but its a doubt. While going through one of the source codes of an application, I saw a piece of code inside a class
private string fname;
public string FirstName
{
get
{
return fname
}
set
{
fname = value;
}
}
Can anyone tell me what it means. I understand that when we declare a class we access fname using an alias FirstName. If it's for some security purpose then what?
This code is also equivalent to:
public string FirstName { get; set; }
What this do is define a property. In C# properties provide encapsulation for private fields.
You can write your custom logic on your property. F.e, some validation:
public string FirstName
{
get
{
return fname;
}
set
{
if (value.Count(s => Char.IsDigit(s)) > 0)
{
throw new Exception("Only letters allowed");
}
fname = value;
}
}
fname is a field and has private visibility but FirstName is a public property therefore it will be visible outside of the class and can contain logic inside get and set methods
It's called Properties (MSDN article). The reason for using them is to encapsulate accessing some class field to be able to easily change class behavior in future if needed.
This is also equivalent to so called auto-property, since the property at this moment oftimedoes not add any logic:
public string FirstName { get; set; }
get and set methods are called accessors(getters) and mutators(setters) these methods are used to access and mutate the attributes of an object without allowing the access from outside the class.
See that access modifier of the variable fname is private which means it can only be accessed by any method inside the class.
and note that the get and set methods should normally be given the public access modifier which enables the method to be accessed from any outside class.
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).
So, let's say I have a C# class like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.
Is this possible?
Edit:
I want to do this without defining a backing field.
Not generally; a few options though;
inherit from ContextBoundObject - which does allow this, but at a performance cost
write an explicit property (i.e. with a backing field), and add a utility method call manually
look at compile-time weavers, such as PostSharp - generally by spotting an attribute or similar
look at runtime code generators, as offered by some DI/IoC tools (and some other "decorator" based tools) - which either decorate or subclass your object to add the extra code
It is possible to do directly in the property body itself, but then you need to use a proper backing field instead of auto-implemented properties.
private string firstName;
public string FirstName
{
get { return firstName;}
set
{
if(check(value))
{
firstName = value;
}
}
}
Even with auto-implemented properties you get a backing field - this is generated by the compiler and you don't have direct access to it.
Edit:
Seeing as you don't want a backing field, you have other options - using an AOP tool such as PostSharp could help with that.
You will have to write the properties in full to achieve this.
I know this has been properly answered but I'll include an example to show you the syntax to achieve what you want:
public class Person
{
private
public string FirstName
{
get
{
return _firstName;
}
set
{
// see how we can call a method below? or any code for that matter..
_firstName = SanitizeName(value);
}
}
}
Are you in a position to rewrite your class to implement an interface? If so, Unity's interface interceptor might give you what you need. If an interface is not an option then that link also documents Unity's type and instance interceptors.
Not out of the box. You would need to insert code into each properties setter and getter, either manually or automatically using IL rewriting.
When you want to do it manually, you can't use automatic properties any more.
When you want to do it automatically, have a look at AOP.
Yes, of course...
In your example you are using automatic properties, without a backing field.... You just need to create a backing field for your property, and then you can do what you want in the setter and getter.
example:
private string firstName;
public string FirstName
{
get { return firstName; }
set { doMethod(); firstName = value;}
}
Mocking frameworks can do this, as well as IoC libraries like Unity. The only other way to do such a thing would be to use IL-rewriting (as previously mentioned).
You cant use automatic properties. You would have to dinfe the property out the old fashion way with a backing field and call the method manually.
public class Person
{
private string _FirstName;
public string FirstName
{
get
{
return _FirstName;
}
set
{
SomeMethod();
_FirstName = value;
}
}
private void SomeMethod()
{
//do something
}
}
As far as I know, you have to use a backing field and put the call to the other method inside the setter thusly:
public class Person {
private string firstName;
private string lastName;
public string FirstName {
set {
DoSomeStuff();
firstName = value;
}
get { return firstName; }
}
public string LastName {
set {
DoSomeStuff();
lastName = value;
}
get { return lastName; }
}
}
In C# do properties need to reference private member variables, or can I just declare the properties and use them directly in the class code?
If the former is the best practice, then does that rule out using C# property short-hand? I.e.
public string FirstName { get; set; }
Properties, when implemented like this:
public string FirstName { get; set; }
Automatically create a private member variable (the compiler does this for you), so you don't have to worry about it. This will behave exactly the same as if you do:
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
There is no reason not to use the automatic properties ( { get; set; } ). The provide the same advantages as making your own private member variable.
In addition, if you later decide you need to do extra processing (for example, if you decide to implement INotifyPropertyChanged in your property setter), you can add this without changing your public API, but putting a backing field in manually.
You don't need properties to access private fields but in general it is considered best practice.
And you can use auto-properties (short hand) untill you need to add more functionality to a property, like validation. Changing it to a 'real' property is always a non-breaking change.
Properties created like this
public String Caption{ get; set; }
this will be compiled as
[CompilerGenerated]
private string <Caption>k__BackingField;
public string Caption
{
[CompilerGenerated]
get
{
return this.<Caption>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Caption>k__BackingField = value;
}
}
The above code is extracted after compilation using reflector tool.
They do not need to reference private member variables. You can use them directly in the class.
Properties do not need to reference private member variables. It is best practice, though, to have them do so. You can think of properties as methods if it makes it easier to understand. You can run code inside of them. You can return whatever you want. You can call methods and use private member variables. You can even simply return a constant.
I use private member variables in almost all cases. It allows me to create a readonly property, or to provide some rules to those outside my class of getting or setting properties that my class doesn't have to follow.
To add on to Reed's answer, inside of your code (within the class itself) the member functions should adhere to this and actually use the Property rather then the actual private member. For instance if you had this:
public string FirstName { get; set; }
And you had a strange method called public char GetFirstLetter() that returned the first letter in a person's first name you'd want to do it like this:
public char GetFirstLetter()
{
return FirstName[0];
}
Instead of actually using your private variable. When you set a property a programmer may have written code to set it in a particular manner. So it only makes sense to simply use that property within your class methods.
C# can reference private variables as in:
public class A
{
private string _b;
public string B
{
get { return _b; }
set { _b = value; }
}
}
The get;set; designation is automatic properties which when compiled will generate the private variable for you, as a way to make it easy to setup your code.
Using properties is the best way to provide a method of control and security to the attributes in a class, always keep the attributes private if possible.
if you use like
public string FirstName { get; set; }
compiler will automatically adds getters and setters for this property automatically.it not a bad practice.
Here is the proof
if you declare
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
like this also compiler will takes it as
so its not ruled out... :)