Reputation: 2339
Is there any time it is good to use a public field in c# instead of a property? And if there is no good case to use them, why are they available in the language?
Upvotes: 2
Views: 171
Reputation: 41393
In general, public read-only fields are useful. They are also useful in structs, especially for interop purposes, such as:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
/// <summary>
/// The x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Left;
/// <summary>
/// The y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Top;
/// <summary>
/// The x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Right;
/// <summary>
/// The y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Bottom;
}
Upvotes: 1
Reputation: 12904
If you do not require any internal processing, then use a Public Field.
For example;
public string Description;
will work exactly the same as
private string _description;
public string Description
{
get { return _description; }
set { _description= value; }
}
However, the latter will allow you to do other things;
public string Description
{
get {
//Do something here
}
set {
//Do something here
}
}
Upvotes: 0
Reputation: 1060
.NET properties are purely a syntax sugar, nothing else. CLR creates the same set/get methods with baking field under the hoods anyway. This is slightly more OOP to have a public property and not to expose public fields, and it brings you the ability to control the validation of the entry, for instance, on setter.
Upvotes: 0
Reputation: 2344
Public Fields break the principal of encapsulation, exposing internal state of your class object to the world. That does not mean you would or should NEVER do that but it is a better practice to expose your internal state through properties so you can provide validation or other protection techniques to keep malicious users from randomly changing your state in a potentially dangerous manner. Of course you can also write logic in your class methods to verify proper state as well so what suits you.
Upvotes: 4
Reputation: 26
I have also noticed that when you are using variable on an ASP.NET page then you might need to declare the variable as public in the code behind. Not sure if there is another way to do it.
Upvotes: 0
Reputation: 6515
It is slightly more efficient to use public static readonly string
than public static string{get;}
as the former eliminates the method call overhead. On the other hand, I think this would be optimized away by the compiler.
Upvotes: 0
Reputation: 2364
Constants is one big instance I can think of. If you have a class that basically just provides data in the form of constants (strings, ints, etc), it doesn't make sense to have a property for each one.
Upvotes: 1