83323

Do you use Data Members or Public Properties from within the Class itself?

Question:

If I have a simple class setup like this:

class MyClass { private string _myName = string.Empty; public string MyName { get { return _myName; } } public void DoSomething() { // Get the name... string name = string.Empty; name = _myName; // OR name = MyName; // ...and do something with it... } }

Which should I use, the public property, or the data member?

Obviously, in this example it doesn't make a difference, since they both just reference the same variable. But what about real world uses of Public Properties?

In general, do Public Properties perform very little, in which case it is OK to call them? Or do people put a lot of functionality into their Public Properties that should not be called by internal class references?

I saw something in another post about NOT putting lots of functionality into Properties, since examining them in the Debugger can perform unexpected results. Is that true?

Answer1:

Use the property - any logic that may be encapsulated within the setters and getters ought to apply, even within the class itself. If there is no logic within the getters and setters it is still not safe to use the fields themselves because if at any point you wish to add logic around the access to those fields you will have to refactor much more.

Answer2:

I believe that you should reference the property as a general practice. While in this particular example it really doesn't make much of a difference, the get/set accessors offer the ability to do a bit more work when grabbing a property. For example, many of our property "get" accessors perform some lookup within a more complex data structure or set default values if nothing has been defined. So that the rest of the class can take advantage of this logic, we make a habit of using the properties. Just so we don't have to think too hard about it, we try to generalize the practice.

There may be instances in which we want to directly access the underlying data member, but then that is a conscious decision with a specific reason and it tends to be the exception.

Answer3:

I prefer properties because they easily handle read-only situations and it's easy to wrap them with any basic validation you might need to do.

Answer4:

If I'm just returning the value of the internal variable, I make the variable public - there's no harm to doing so. I've always used Public Properties when I want to do something in response to either a viewing or a changing of the value - ie, write it to a database, set something else too (as in the second part of your example).

The question you have to ask is whether you want what happens inside your class to trigger these events. If you do, the same way an external caller would, then access the values via the property. If you just want to read the value, use the internal variable.

To answer your question, there's no harm to doing it either way - just consideration of the potential side-effects.

Recommend

  • Is it possible to detect unreachable code or other built in compile warnings using Roslyn
  • Question about POP3 message termination octet
  • TensorFlow Custom Allocator and Accessing Data from Tensor
  • How to check Eclipse plugin performance
  • CUDA Debugging - VS on windows workstation, GPUs on Linux server?
  • CSS - how to trim text output?
  • Bootstrap collapse within a foreach loop
  • Pointer vs Reference difference when passing Eigen objects as arguments
  • LNK1104: cannot open file 'kernel32.lib'
  • RegistryKey.GetSubKeyNames returns names that are not in that subkey!
  • Regex for Specific Tag
  • Connecting bluetooth device to windows phone 8 application
  • Can you pass an array from javascript to asp.net mvc controller action without using a form?
  • Can my PDF ping my server when it is opened?
  • How to pass solution folder as parameter in command line arguments (for debug)?
  • How can we prepend rows to a react native list-view?
  • Jquery Mobile pageLoading() Method how does it work?
  • CXF JAXB JAXBEncoderDecoder unmarshalling error : unexpected element when having qualified elements
  • Unexpected token ILLEGAL while running node.js mocha test
  • Pycharm: Marking a folder as 'sources root' is not recursive for subfolders
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • What's the purpose of QString?
  • Installing iPhone App to iPhone
  • Jackson Parser: ignore deserializing for type mismatch
  • Abort upload large uploads after reading headers
  • Java: can you cast Class into a specific interface?
  • Debugging ASP.NET on a built-in web server suddenly stops
  • Is there a javascript serializer for JSON.Net?
  • Adding a button at the bottom of a table view
  • AES padding and writing the ciphertext to a disk file
  • Updating server-side rendering client-side
  • How to extract text from Word files using C#?
  • Data Validation Drop Down Box Arrow Disappearing
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Free memory of cv::Mat loaded using FileStorage API
  • Memory offsets in inline assembly
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • Turn off referential integrity in Derby? is it possible?
  • Checking variable from a different class in C#
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize