Tarmo Tarmo - 1 year ago 63
C# Question

What is the optimal way to return a private value from inside a class?

I'm attempting to optimize my code for maximum readability and for that I need my code to be in-line through and through. I will present two snippets of code as an example. In my eyes the below one is more easier for the eyes. These snippets (one of them) would be stored in a class and setting width should only be possible inside the class while getting Width should always be possible.


private int width;
public int Width
get { return width; }
private set { }


private int width;
public int Width()
return width;

As far as I am concerned these two ways of achieving the same end result are identical. Because I would like to be thoroughly in-line in all my classes I wouldn't want to use both ways mixed together. The B-approach seems cleaner in my eyes.

Are there any downsides/upsides to either approach. Should one approach be favored over the other? Are A and B approaches really completely identical?

Answer Source

Not sure why everything has to be thoroughly in-line, or why that makes anything more readable.

This this would seem to be the most concise implementation in any case.

public int Width 
    private set; 

Remove the white space if you really must but I'm not sure if that's really an improvement.

public int Width { get; private set; }

The MSDN offers some guidance in this situation:

In most cases, properties represent data and methods perform actions. Properties are accessed like fields, which makes them easier to use. A method is a good candidate to become a property if one of these conditions is present:

  • Takes no arguments and returns the state information of an object.
  • Accepts a single argument to set some part of the state of an object.

Properties should behave as if they are fields; if the method cannot, it should not be changed to a property. Methods are better than properties in the following situations:

  • The method performs a time-consuming operation. The method is perceivably slower than the time that is required to set or get the
    value of a field.
  • The method performs a conversion. Accessing a field does not return a converted version of the data that it stores.
  • The Get method has an observable side effect. Retrieving the value of a field does not produce any side effects.
  • The order of execution is important. Setting the value of a field does not rely on the occurrence of other operations.
  • Calling the method two times in succession creates different results.
  • The method is static but returns an object that can be changed by the caller.
  • Retrieving the value of a field does not allow the caller to change the data that is stored by the field.
  • The method returns an array.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download