Should we initialize List(T) with size if known ?

As per documentation, it says

If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the List.

We can decrease the capacity of a List(T) any time by calling TrimExcess method over the List(T).
If we decrease the capacity, interestingly, it is not decreased, but the memory is relocated and all the elements in the List(T) are copied into that memory location.

dafault capacity if not defined is “0”. A List doubles itself, every time the capacity limit is hit.

Capacity for the List could be checked easily, any time using List(T).Capacity property.

           List<string> animals = new List<string>();

            animals.Add("cow");
            animals.Add("bull");           

            // get List<string> capacity
            int listCapacity = animals.Capacity;
          
            // get List<string> size
            int listSize = animals.Count;

            // reduce capacity 
            animals.TrimExcess();

            // make Lis<string> empty
            animals.Clear(); 
Advertisements

Check if class(T) inherits an interface(T)

The very first thing which comes to our mind is is operator like

bool IsDerived = a class is Interface

Well, that is not correct. why ? because

is operator is used to check whether the run-time type of an object
is compatible with a given type.

An expression where the use of is conforms to the syntax, evaluates to true, if both of the following conditions are met:

  • expression is not null.
  • expression can be cast to type. That is, a cast expression of the form
    (type)(expression) will complete without throwing an exception. For
    more information, see 7.6.6 Cast
    expressions.
  • Solution is to use:

    bool IsDerived = typeof(ISomeInterface).IsAssignableFrom(typeof(T));

    References

  • Does a Type Implement an Interface?
  • is operator