0

I am trying to understand proper usage of Field and whether field should be allowed to access by other class or it should be always be through property?

Consider i have a code like below :

internal class MyCalculator : IDisposable
    {
        public Type1 type1;
        public MyCalculator(Type1 type1)
        {
           this.type = type1;
        }
    }

internal class Accessor
{
   public void Foo()
   {
     MyCalculator obj = new MyCalculator();
     obj.type1.Id = 10;
   }
}

Is this a good practice of allowing access of public fields outside of another class or it should always be through property only?

While I was checking source code of List i saw this :

public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
    {
        private const int _defaultCapacity = 4;

        private T[] _items;
        [ContractPublicPropertyName("Count")]
        private int _size;
        private int _version;
    }

private properties are marked with underscore while same Dictionary private members were not marked with Underscore as shown below :

public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback  {

        private struct Entry {
            public int hashCode;    // Lower 31 bits of hash code, -1 if unused
            public int next;        // Index of next entry, -1 if last
            public TKey key;           // Key of entry
            public TValue value;         // Value of entry
        }

        private int[] buckets;
        private Entry[] entries;
        private int count;
        private int version;
        private int freeList;
        private int freeCount;
}

So i am bit confused is there any difference between above 2 i.e List and Dictionary private members or may be i am missing something?

This is not duplicate exactly because I have asked too things and ofcourse i could have mention that in the question but since i did not wanted question of my title to be too big.

Also I am asking this in context of what I have shown in my code(Field and Property code snippet) and whether its a good practice or not in my specific scenario.

I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216

2 Answers2

2

According to this:

There are times when you could use non-private fields, because for whatever reason you don't care about the compatibility reasons above. However, there are still benefits to using properties even for trivial situations:

-There's more fine-grained access control with properties. Need it to be publicly gettable but really only want it set with protected access? No problem (from C# 2 onwards, at least).

-Want to break into the debugger whenever the value changes? Just add a breakpoint in the setter.

-Want to log all access? Just add logging to the getter. Properties are used for data binding; fields aren't.

In almost all cases, fields should be private. Not just non-public, but private. With automatic properties in C# 3, there's basically no cost in readability or the amount of code involved to use a property instead of a field. Very occasionally you might find a genuinely good reason, but think long and hard about it before committing to that choice, particularly if you'll be exposing it beyond internal access.

and for the underscore:

There's no language-defined meaning - it's just a convention some people use to distinguish instance variables from local variables. Other variations include m_foo (and s_foo or g_foo or static variables) or mFoo; alternatively some people like to prefix the local variables (and parameters) instead of the instance variables.

just when ever you want to create a variable inside class put a simple {set;get;} in front of it. no harm done.

public int a {set; get;}
Abbas Dehghan
  • 381
  • 4
  • 12
1

Best practice is to use properties instead of direct access to fields, whenever it's possible. This enables better debugging and encapsulation.

Regarding the underscore, a private field is a private field. Its name does not change its accessibility. It's a matter of naming convention, maybe two different teams worked on List and Dictionary and they named thing differently.

Generally C# developers tend to avoid underscore, but an exception can be made for private fields (see here)

Mario Cianciolo
  • 1,223
  • 10
  • 17