After reading Jon Skeet’s excellent C# in Depth - again (3rd edition - to be published soon) I’ve decide to try and actually read the C# language specification…
Being a sensible kind of guy I’ve decided to purchase the annotated version which only cover topics up to .NET 4 – but has priceless comments from several C# gurus.
After I’ve read a few pages I was amazed to learn that a few things I knew to be true were completely wrong and so I’ve decided to write a list of new things I’ve learnt while reading this book.
Below you’ll find a short list of new things I learnt from reading the 1st chapter:
Not all value types are saved on the stack
Many developers believe that reference types are stored on the heap while value types are always stored on the stack – this is not entirely true.
First it’s more of an implementation detail of the actual runtime and not a language requirement but more importantly it’s not possible – consider a class (a.k.a reference type) which has a integer member (a.k.a value type), the class is stored on the heap and so are it’s members including the value type since its data is copied “by-value”.
// stored in heap
int a = 5;
For more information read Eric Lippert’s post on the subject – he should know.
What the hell is “protected internal”
If you’ve written more than one class you’ve probably used public/internal and protected access modifier:
// Can only be accessed by MyClass
private object a;
// Accessible by MyClass and classes that derive from it
protected object b;
// Accessible by this assembly
internal object c;
// Accessible by everyone
public object d;
So what does protected internal means?
Some believe that members marked as “protected internal” are only accessible for classes that derive from MyClass AND are defined at the same assembly in fact it means that classes that derive from MyClass OR are defined on the same assembly as my class can access that member. So it’s just like using internal and protected at the same time – confused yet?
Use only immutable types as a readonly fields
How many times have you marked a field readonly?
You probably did it to make sure that a field cannot change after initialization – think again:
static readonly Person Me = new Person("Dror", "Helper");
public void UpdateFail()
// Compilation error!
Person.Me = new Person("Kaiser", "Soze");
public void JustBecauseYouCan()
// This would work!
Person.Me.First = "Kaiser";
Person.Me.Last = "Suze";
That’s right, while you cannot replace the the readonly field – you can update the heck out of it.
Of course there’s more, I choose these examples because they helped me understand C# better.
I hope to add more such insights as I continue reading the book – so stay tuned…
Labels: .NET, Book review, C#