This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
What is the difference between a field and a property?
(33 answers)
Closed 7 years ago.
Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?
CASE 1:
private static int number = 1;
public static int Number
{
get { return number; }
set { number = value; }
}
CASE 2:
public static int Number
{
get;
set;
}
I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.
The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.
Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.
We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:
private int mNumber;
public int Number
{
get
{
return Number;
}
set
{
if (Number == 8)
{
throw new CannotReceive8Exception();
}
else
{
mNumber = value;
}
}
}
If you look at the decompiled code of this code:
public int Number { get; set; }
You will see that the compiler has added a background private field anyway:
While there is no difference to the compiler, since it would generate the fields for you, I prefer to leave my code clean and just use
public int Num {get;set;}
in one line, since there is no supreme meaning to explicitly typing the code and keeping it in one line allows me to differentiate properties like this from methods, which span across multiple lines at glance.
Related
This question already has answers here:
Is Int32.ToString() culture-specific?
(7 answers)
Closed 7 years ago.
Ok i am going through Saplo Api C# project. It stump me when i saw these code:
public class Helper
{
private static int _currentId;
public static int GetCurrentId()
{
return _currentId;
}
public static int GetNextId()
{
return ++_currentId;
}
}
[DataContract]
internal class RequestBase<T>
{
public RequestBase()
{
ID = Helper.GetNextId().ToString(CultureInfo.InvariantCulture);
}
public RequestBase(string method, T #params)
: this()
{
Method = method;
Parameters = #params;
}
[DataMember(Name = "id")]
public string ID { get; private set; }
[DataMember(Name = "method")]
public string Method { get; set; }
[DataMember(Name = "params")]
public T Parameters { get; set; }
}
So if you look at the constructor for RequestBase.... public RequestBase()! you will see Helper.GetNextId() this only return an int why bother using CultureInfo.InvariantCulture i dont understand why a simple ToString inst good enough to do the job or what, isnt this is just more overhead?
When it comes to integers, there is currently no recognized, official culture that would affect how Int32.ToString() behaves. It will always create an identical string.
However, that does not mean that a custom culture might not interpret the results differently. Resharper and other code style tools typically recommend using a culture to maintain consistency.
It is worth noting, when travelling outside of integers, cultures absolutely make a difference. For instance, in EN-US, commas are used for thousands separation and periods are used to represent the decimal point. On the other hand, in EN-GB it's the opposite. Keeping consistency between value types could certainly be viewed as a good habit.
That said, in this case, yes, providing CultureInfo for integers is probably unnecessary "overhead", unless you prefer to keep consistency in your codebase.
In this case it doesn't seem necessary. I know plugins like ReSharper and StyleCop will complain(show a warning) about an empty ToString() unless you tell them not to. It's possible one of these plugins was used when writing this code.
Generally CultureInfo.InvariantCulture is used when converting dates and decimal/currency values.
This question already has answers here:
Public Fields versus Automatic Properties
(14 answers)
Closed 9 years ago.
Example 1:
class Class1
{
public static int A = 1;
}
Example 2:
class Class2
{
private static int _A = 1;
public static int A
{
get
{
return _A;
}
set
{
_A = value;
}
}
}
Assuming that I don't want to do any validation and perform any extra functions. I just want to hold the plain data. Both Class1.A and Class2.A have the same result. New number can be assigned to both too. So what is the different for doing this? Is there any benefits? Why and When should I use them?
If there is no difference between them, I should use Example 1, as Example 1 only requires 1 line of code and Example 2 requires 6-10 lines. Do you agree?
The technical difference is the presence of get and set accessors. You can customize either or both to do more that just get or set the value.
The practical difference is that many data-binding methods (including most if not all of the .NET controls) use reflection to bind to properties only - they do not support binding to fields directly.
If you plan to bind the properties of your class to a UI control (DataGrid, TextBox, etc.), or if there's the slightest chance that you might customize the get/set accessors in the future, then make the properties. It is a breaking change to change a field to a property.
Many coding standards (including FxCop) hold that you should use properties instead of fields for public data.
If lines of code are a concern you can use auto-implemented properties:
class Class2
{
public static int A {get; set; }
}
You can later add logic to the get/set accessors without breaking users of your class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#?
Difference between Property and Field in C# .NET 3.5+
Some time ago I inherited a C# web app wherein most class members that could be fields are defined as properties in one of the following two manners:
private Guid id;
public Guid Id
{
get { return id; }
set { id = value; }
}
public int someValue{ get; set; }
Namely, the getters/setters don't do anything other than ferry a value to/from a private field. In these cases, is there an advantage [or justification] for building these members out as properties vs. fields? And vice versa?
Would I be violating any unspoken rules or best practices by changing them to fields? Is there a notable performance difference -- for instance, incrementing someValue for a list of N objects one way or the other? (My current understanding is that field access is necessarily less complex [and efficient].)
It's mainly an OOP (Object Oriented Programming) notions: Encapsulation
You can view a brief description here;
WikiPedia entry on Encapsulation
One of the possible uses is for example when trying to assign a value, to call a function to validate this new value. For example:
private Guid id;
public Guid Id
{
get { return id; }
set
{
if (checkValue(value)==true)
{
id = value;
}
}
}
Simple question I imagine, but what is the difference between these lines of code:
Code 1
public int Temp { get; set; }
and
Code 2
private int temp;
public int Temp { get { return temp; } }
My understand was that an automatic property as per Code 1 would perform the exact same function as Code 2?
I'm reading Head First C# and I'm finding it hard to understand why it's using two different ways of doing the same thing?
The primary difference between your Code1 and Code2 is that in #1, the property is settable.
You can achieve the same thing using automatic properties, because the setter can be private:
public int Temp { get; private set; }
Automatic properties was added in C#3, and is really just syntactic sugar for the longer version using a field. If you don't need to access the field directly, there is no reason not to use automatic properties. Automatic properties are equivalent to using a field - the compiler generates the field for you, it is just not accessible in code.
The first one is a writable property.
It's equivalent to
private int temp;
public int Temp {
get { return temp; }
set { temp = value; }
}
(except that you can't use the backingfield directly), but it requires 1 line of code instead of five.
When writing classes with 5 or 6 simple properties, auto-properties can make the classes much shorter.
You can make read-only auto-properties by writing
public int Temp { get; private set; }
The "automagic" property is just a "short-hand" notation:
public int Temp { get; set; }
is just a lot simpler to type than
public int Temp
{
get { return _temp; }
set { _temp = value; }
}
but functionally equivalent. Just a nice "shorthand" to improve your productivity, but no additional or magic functionality, really.
If your second example had both a getter and a setter, they would be functionally equivalent.
As it stands now, the first is publicly gett-able but can't be set publicly. You could also achieve the same thing using auto properties:
public int Temp { get; private set; }
And in case you're curious, automatic properties still get a backing private field. That bit is just handled by the compiler for you so that life is easier.
As for the reason why I would use property with a backing field is when I want to do something else when getting or setting the property. For example, a validation routine embedded into the property itself, or caching, etc...
Otherwise, for simple get and set, I'd use the automatic property format. It's more compact and involves less coding which I think it's a good thing.
This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
Closed 9 years ago.
Are there any further benefits to the "new", shorter way to handle properties, other than shorter code - like performance benefits, less memory usage etc.?
Writing
public string StrVariable { get; set;}
Rather than
private string strVariable;
public string StrVariable
{
set
{
strVariable = value;
}
get
{
return strVariable;
}
}
And are there any drawbacks - perhaps some would argue the code is less readable, less explicit?
Heres a link you may find useful.
One big drawback in a specific scenario - you lose control of the field name. This might sound insignificant, but it is a big problem if you are using binary serialization (via BinaryFormatter).
Other things:
they can't be readonly at the field level
for structs you need to call : this() in custom constructors
They do, however, do a fantastic job in 99% of cases - they express the code neatly, while leaving it possible to add extra implementation details later (by switching to explicit fields) without breaking calling code (except for the points above).
One drawback I can see is if you want to do something else in the get/set routines. Increment a counter or something of that sort. Maybe validate the input if you haven't already.
Collection properties are one issue as well. They are not initialized with Autoproperties.
Example:
public class foo
{
public List<String> S1 { get; set; }
private List<string> s = new List<string>();
public List<String> S2
{
get { return s;}
set { s = value; }
}
}
foo f = new foo();
f.S1.Add("thing");
f.S2.Add("thing");
f.S1.Add will bomb with a nullref exception.