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.