text
stringlengths
0
13.4k
var itemCount = readOnlyGroceryList.Count; // There are currently 2 items
//readOnlyGroceryList.Add("Candy"); // Compiler Error - Items cannot be added to a
ReadOnlyCollection object
groceryList.Add("Vitamins"); // ..but they can be added to the original collection
itemCount = readOnlyGroceryList.Count; // Now there are 3 items
var lastItem = readOnlyGroceryList.Last(); // The last item on the read only list is now "Vitamins"
View Demo
Section 6.3: Warning: Elements in a ReadOnlyCollection are
not inherently read-only
If the source collection is of a type that is not immutable, elements accessed through a ReadOnlyCollection can be
GoalKicker.com – .NET Framework Notes for Professionals
24
modified.
public class Item
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public static void FillOrder()
{
// An order is generated
var order = new List<Item>
{
new Item { Name = "Apple", Price = 0.50m },
new Item { Name = "Banana", Price = 0.75m },
new Item { Name = "Vitamins", Price = 5.50m }
};
// The current sub total is $6.75
var subTotal = order.Sum(item => item.Price);
// Let the customer preview their order
var customerPreview = new ReadOnlyCollection<Item>(order);
// The customer can't add or remove items, but they can change
// the price of an item, even though it is a ReadOnlyCollection
customerPreview.Last().Price = 0.25m;
// The sub total is now only $1.50!
subTotal = order.Sum(item => item.Price);
}
View Demo
GoalKicker.com – .NET Framework Notes for Professionals
25
Chapter 7: Stack and Heap
Section 7.1: Value types in use
Value types simply contain a value.
All value types are derived from the System.ValueType class, and this includes most of the built in types.
When creating a new value type, the an area of memory called the stack is used.
The stack will grow accordingly, by the size the declared type. So for example, an int will always be allocated 32 bits
of memory on the stack. When the value type is no longer in scope, the space on the stack will be deallocated.
The code below demonstrates a value type being assigned to a new variable. A struct is being used as a convenient
way to create a custom value type (the System.ValueType class cannot be otherwise extended).
The important thing to understand is that when assigning a value type, the value itself copied to the new variable,
meaning we have two distinct instances of the object, that cannot affect each other.
struct PersonAsValueType
{
public string Name;
}
class Program
{
static void Main()
{
PersonAsValueType personA;
personA.Name = "Bob";
var personB = personA;
personA.Name = "Linda";
Console.WriteLine( // Outputs 'False' - because
object.ReferenceEquals( // personA and personB are referencing
personA, // different areas of memory
personB));