Skip to main content

Posts

Showing posts with the label list

How to NOT expose a read only collection in C#

These days I had the opportunity to make a review over an ecommerce application. They tried to use CQRS and they almost succeeded.  I notified a problem on their queries classes that can become a big problem in time, if you want to sell this solution as a platform. Also, from some perspective, these problems also violate the CQRS principle. Let’s see some code now: public class Order { Collection<OrderItem> _items; public IEnumerable<OrderItem> Items { get { return _items; } } ... } What do you see here strange?  We want to expose the OrderItem collection as a read only collection. To do this, we convert it to IEnumerable. Hmmm… sounds good? Nope. Big mistake! Nobody stop us to convert the Items back to an ICollection and Add/Remove items from it. Order order = new Order(); … var orderItems = (Collection<OrderItem>)oder.Items; What should we do? .NET framework has specials collections that can...

Convert a collection of items to a string

Sunt cazuri cand avem liste pe care dorim sa le convertim intr-un string folosind un anumit delimitator. List<string> lista=new List<string>(){ "A" , "B" , "C" }; //Output: A, B, C, LINQ nu contine o solutie directa, putem incerca sa interam cu un foreach toate elementele din lista si sa le adaugam la un StringBuilder StringBuilder sb=new StringBuilder(); string format = "{0}, "; lista.ForEach(item => sb.AppendFormat(format, item)); Dar din pacate codul scris mai sus este echivalent cu un foreach clasic, doar ca iteram folosind LINQ. O solutie este sa folosim metoda String.Join, care primeste doi parametrii: -delimitatorul; -un array care contine lista de string-uri; Aceasta metoda functioneaza fara probleme, singura problema care o are este ca nu functioneaza pe obiecte generice de tip IEnumerable. Pentru a rezolva acest neajuns este sa apelam la extension method si sa ne scriem propria noastra metoda pentru IEnumerable. /// <...