They can be both according to meaning. Most of DateTime's properties are calculated fields. DateTime is represented by a long and all its properties are calculated based on that value.
views:
157answers:
3Whether you decide to make a property static or not should be determined by the semantics of that particular property, not whether it's backed by a field.
Whether a property is static or instance depends on it's purpose and meaning.
The reason that DateTime.Today
is static is because it is actually returning an instance of DateTime
- it would be awkward to first have to create a DateTime
to then call an instance method (or instance property) to get the current date.
You should consider making a property static if:
- It does not represent the state of a particular object instance.
- It is not get written to - or if written to is designed to be thread-safe. (You have to define what thread safe means, of course).
- It is a factory property that is used to return an instance of an object (singleton accessor properties come to mind).
- You don't expect to need an instance property with the same name (C# does not allow duplicate named properties that only differ by whether they are instance vs. static).
Otherwise, the property probably needs to be an instance property - or perhaps a method.
Some interesting examples of static properties in .NET itself include:
- Singleton accessor properties.
- DependencyProperty definitions in WPF
- Globally accessible readonly state, like the Culture instances for formatting strings.
EDIT: In thinking about places where instance v. static properties are used in .NET, the Thread class comes to mind as an example of a class that is confusing in its choice of when to use which.
For example, the CurrentPrincipal
property is a static property while CurrentCulture
property is an instance property instead. It's unclear if there is any benefit in this organization - it seems (to me) that all of the static properties of Thread
could have been made instance properties (except CurrentThread
) without losing any expressive power, but adding consistency and clarity to the public interface.