Is there some internal difference between the C# syntactic sugar way of making properties:
public string FirstName { get; set; }
and just making public variables like this:
public string LastName;
I assume the first way is preferred and the second to be avoided. However, I often see this type of readonly property being used which is a form of the second type above:
public readonly string InternalCode;
Is this a best-practice way to create readonly property?
using System;
namespace TestProps
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.FirstName = "Jim";
customer.LastName = "Smith";
customer.Show();
}
}
class Customer
{
public string FirstName { get; set; } //prefered
public string LastName; //avoid
public readonly string InternalCode; //???
public Customer()
{
InternalCode = "234729834723984";
}
public void Show()
{
Console.WriteLine("{0}, {1} ({2})", LastName, FirstName, InternalCode);
Console.ReadLine();
}
}
}
Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.
C doesn't have a keyword "public", so it's probably a macro defined in the less source code somewhere.
Use of the Global Variable in CThe global variables get defined outside any function- usually at the very top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that gets defined for that program.
A public variable represents a violation of one of the basic principles of object-oriented programming, namely, encapsulation of data.
Since he didn't answer (yet) and no one else referenced this yet: There is a great article on this topic by Jon Skeet amending his book C# in depth (give credits to Jon):
Why Properties Matter
Using a property provides an interface which is more resistant to change in the future. Let's say some time in the future, a decision is made to add a prefix to the internal code.
Using a public readonly variable exposes your internal structure and you will have a hard time adding the prefix to every line you used the internal variable of the class.
Using a Property, you can just write the following
public string InternalCode {
get { return _prefix + _internalCode; }
}
and you're done!
In my opinion, it's ok to expose public fields (especially if they're readonly or const). Having said that, I'd say that in the example you're presenting, I'd probably go with properties since they'll give you 2 advantages (over fields): 1) better encapsulation and may let you adapt your code in the future and 2) if you're doing data binding, then you do need the properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With