February 5, 2015

Post-increment confusion

Recently answering a question about post-increment behaviour and then asking around a bit convinced me that this concept is still misunderstood by many. Apparently, different languages can interpret some post-increment statements differently, so I’ll stick to the .NET platform as I’ll try to clarify how it really works.

To start with something simple, we can all agree on the fact that the following code snippet

int a = 10;                        
int b = a++;

stores 10 in a variable a, then copies the value to a variable b and increases value stored in the variable a to 11. But what the following code does?

int a = 10;                        
a = a++;

In order to be sure, let’s peek at generated IL code (you can try it yourself using LINQPad, for instance).

IL_0001:  ldc.i4.s    0A // stack: 10
IL_0003:  stloc.0        // a = 10, stack: empty
IL_0004:  ldloc.0        // stack: 10
IL_0005:  dup            // stack: 10, 10
IL_0006:  ldc.i4.1       // stack: 10, 10, 1
IL_0007:  add            // stack: 10, 11
IL_0008:  stloc.0        // a = 11, stack: 10
IL_0009:  stloc.0        // a = 10, stack: empty

I supplemented the output by comments to see what’s happening on the evaluation stack. As you can see, in order to be able to return the previous value, it’s preserved by duplicating it first, then increment takes place followed by an assigment of the new value to the variable and finally the old value returned (as post-increment promises) and assigned to the variable.

I consider the previous nearly self-explanatory and I could leave it as it is now, but admittedly, it’s not always enough to look at the corresponding IL to understand or even start with it for that matter. Therefore, remember that the right side expression of an assignment statement is always evaluated first in .NET. It’s a well defined behaviour of operator precedence and associativity.

To use it in our situation - a++ expression is completely evaluated before a value it returns is assigned to a variable on the left side, which means, that a is really 11 for a moment before it’s overwritten by the previous value.

January 25, 2015

Button with << in content

This post is inspired by a question on SO. Its author defined two buttons in XAML in a WPF application, set content of the first one to >> and content of the other one to << through a Content property but the compiler complained and left him puzzled. Why closing brackets can be used but opening ones cannot?

Untitled
My first guess was that
<Button Content="<<" />

is by the compiler translated to
<Button>
<<
</Button>

before processing, because the two forms are equivalent, but after I’ve done some research I found that this is not true. Why would I even think that? Because I know that bracket matching can be easily determined by pushing opening brackets onto a stack and popping them as closing brackets are read by a text reader. Then it’s clear that it’s syntactically incorrect, because the compiler is confused with opening brackets missing their closing brackets. Two closing brackets are not a problem, if there’s nothing on the stack, then it has to be content. It makes sense. So how it is really?

When you try those two snippets in Visual Studio, compiler provides different error messages in both cases.

In the first case:
  • when you point with a mouse cursor on a Button text underlined with a red squiggly or on the brackets, it says: “XML element is not closed”,
  • when you point right after a closing quotation mark of content, it says: “Whitespace is missing.” and 
  • finally, when you point on a closing tag, it says: “The open angle bracket character ‘<’ is not valid in an attribute. It should be written as ‘&lt;’.”.
In the second case:
  • when you point on brackets, it says: “Invalid tag header” and
  • when you point on a closing tag, it says: “Closing tag for element ‘<>’ was not found.”.
Now we see the difference in how are these two forms processed. One thing to notice is that it actually provides a solution in one of the error messages. Still, the question is why it does not work with two opening brackets?

To explain this behavior we need to know the following:

Button is one of content controls, which are simply controls that are constrained to contain a single item. Content controls all derive from System.Windows.Controls.ContentControl, which has a Content property of type Object that contains the single item. Because a content control’s single item can be any arbitrary object, the control can contain a potentially large tree of objects. There just can be only one direct child. [1]

Having this on mind it’s now clear that in the second case the compiler can actually represent a button’s content as a UIElement if it’s syntactically correct (therefore those two error messages implying creation of a new element) or just print a text. In the first case, it can be only plain text or a markup extension ({…}).

[1] – WPF 4 Unleashed, Adam Nathan

January 12, 2015

Field or property?

While answering questions on Stack Overflow I see developers use fields where properties should be used again and again. And while it was not too much appealing to use properties in times when the feature made it to the language, it became really compelling over the years. With this article, I’ll try to clear all your doubts about using properties instead of public and protected fields.

Why bother with properties?

The first question, why even consider properties as a replacement of public fields?
  1. Encapsulation. When you declare a public field on a type you allow everyone to set its value whenever they want, unless the field is readonly, of course. But what happens if you decide to change the logic of setting it to include some sort of a check, for instance? You would have to add a getter and setter methods and make the field private, which breaks your API. This applies to protected fields too.
  2. Data-binding. Not having to set all UI components manually to a new value whenever you obtain it, but rather let them to change automatically when the source changes, is a huge advantage. You can’t bind to a field, period.

Concerned about performance?

An auto-property is translated into a private backing field with a getter method and a setter method by the C# compiler.
public int Number { get; set; }
// is translated into
private int number;
public int Number
{
    get { return number; }
    set { number = value; }
}
// and getter and setter are nothing else but
int get_Number()
{
    return number;
}

void set_Number(int value)
{
    number = value;
}

“This sure involves a performance penalty, right? A field is just a fiield and it’s accessed directly whereas a property is a field accessed through methods – an extra level of indirection.”

It sure looks like what you think, but the JIT compiler is very clever about this and optimizes it away. How? It’s out of the scope of this article, but I’ll get to it someday. For those eager of you, it’s called inlining.

Writing a property is slower!

You might think that, but did you know that there are code-snippets in VS for different kinds of properties? Try writting prop and press Tab or Enter in order to generate an auto-property and then simply change its type (followed by pressing Tab or Enter) and name. Follows a list of other property code-snippets available in VS:
  • propg – auto-property with a private setter
  • propfull – property in the expanded form
  • propdp – dependency property
As it’s all fast enough when using code-snippets, the only thing that can discourage you from using properties are extra lines of code. If you wanted to use properties before auto-properties (short form of auto-implemented properties) made it to the language in 2007 (C# 3.0), you had to write them in the expanded form shown in the example above. You still need to write them in that manner if you want to
  • include some getter or setter logic or
  • have a truly readonly property (auto-property with a private setter in not readonly).
Good news is that the later one has been revisited for C# 6.0. If you don’t know what I’m talking about, check the following code example.
// auto-property initializers
public int Number { get; set; } = 10;

// getter-only auto-properties
public int Number { get; } = 10;

These two new features combined make a huge difference in resulting number of lines of code. There’s no reason to write
public readonly int number = 10;

anymore, because it simply does not offer any benefits over a property. There may be some scenarios where a public field makes more sense, but I’m not aware of any. If you are, feel free to comment.

January 5, 2015

.NET Fundamentals MTA certification experience

MTA logoI recently took a Microsoft exam 98-372, also known as Microsoft Technology Associate for .NET Fundamentals, and passed it with a score of 78%. I have to admit that I expected a better result after I made it through questions in 30 minutes or so without much sweating. In this article, I'll briefly describe the exam, how did I prepare for it and give away some tips (nothing that an NDA paper I had to sign doesn't allow me to anyway).

You can take the exam either in C# or VB.NET but from my experience, if you are comfortable reading code in both of them, it does not matter which one you choose, because there's no code writting and only handful of code understanding questions. The exam primarily consists of questions with answers provided to pick the best one. Questions are from the following areas:
  • Understanding .NET Framework concepts
    • Understand basic application settings
    • Understand events and event handling in the .NET Framework
    • Understand structured exception handling in the .NET Framework
  • Understanding namespaces and classes in the .NET Framework
    • Understand .NET class hierarchies
    • Understand object oriented concepts in the .NET Framework
    • Understand .NET namespaces
    • Understand and create class libraries
    • Understand and use different data types in the .NET Framework
    • Understand generics
  • Understanding .NET code compilation
    • Understand the fundamentals of Microsoft Intermediate Language (MSIL) and Common Language Infrastructure (CLI)
    • Understand the use of strong naming
    • Understand version control
    • Understand assemblies and metadata
  • Understanding I/O classes in the .NET Framework
    • Understand .NET file classes
    • Understand console I/O
    • Understand XML classes in the .NET Framework
  • Understanding security
    • Understand the System Security namespace
    • Understand authentication and authorization
  • Understanding .NET languages
    • Understand language interoperability
    • Understand type safety
  • Understanding memory management
    • Understand resource allocation
    • Understand the difference between managed and unmanaged applications
Now, you might think that that's quite a lot of area covered, but I would say that it's roughly 15% of the .NET Framework core (no web, desktop, mobile, ...) if not even less. The structure probably has not been changed since it was created. There are no questions on goodies from the latest versions of the .NET Framework like LINQ or TPL. And that is why I do not take the certificate too seriously. It's a great start if you are new to .NET but I would sure want to see more if I should take you aboard.

If you are a .NET newbie who needs to prepare for the exam, I recommend going carefully through every "Preparation resource" provided by Microsoft (you will find link at the end of the article) and trying out every code snippet available there. To get even better understanding, reading most of the articles referred to from those resources is highly recommended.

If you develop on the .NET platform at least few years, you probably know most of the covered topics already. Just go through the list and if you are not really sure that you know enough, read the resources.

I originally thought that I could do the exam without any additional studies whatsoever, but I found out that "Understanding security" includes many subareas I'm not experienced in. I read everything I could get my hands on but it still was my weakest area in which I scored only half of the percentage allocated. So if you have never worked on an application with a security part in it, do not underestimate this area.

I also stumbled in interoperability and event handling, because I never played with things like COM and didn't expect questions on events and delegates be so oddly described. If you know how to work with events and delegates, I still recommend reading this preparation resource and focus on how things are called.

Memory management and code compilation are my favourite areas so no problem there, but I guess they are not widely popular amongst developers, so be cautious there, learns some fundamentals.

Probably the easiest area is "namespaces and classes". You would have to be a real newcomer to make a mistake there. Or I can imagine that if you are not very comfortable reasoning about code outside Visual Studio that you might get easily confused by some questions.

That's about it. Do not underestimate it even if you are a seasoned .NET developer, particularly if you joined the community in last few years and some concepts from the .NET 2.0 are still not very clear to you. If you search the internet you might find some exam examples and get feeling about how questions look like. If you want to know more about the exam, visit the official website, please.

December 29, 2014

A fresh start

moving the ball forward
It's been 15 months since I started with occasional "memory dumping" and I have discovered something that I would like to share with you.

It all started by joining the MSP (Microsoft Student Partner) program in the summer of 2013 when I met some smart people who shared their knowledge through blogging. I was impressed and I created this site a month or so later. But ...

Why? This was a really good question. Why on earth would I spend my time on writing that maybe no one will ever read?

What? How often? I was not sure what I'll write about and how much can I come up with. After all, I was never too chatty.

Where? A private blog or a working portal?

Well, now I know the answers. It was not easy to find them and I quit few times because I was not happy with how things were going, but now I know it was worth persisting, because

You don't start out writing good stuff. You start out writing crap and thinking it's good stuff, and then gradually you get better at it. That's why I say one of the most valuable traits is persistence. - Octavia Butler

I'm writing articles because it's one of the forms of sharing and I have discovered that only by sharing I can find out gaps in my knowledge that I would not find otherwise. When I finish reading a book or a white paper I feel that it's all clear to me; well, at least until I try to explain it to someone else. Only then I realize that it's mostly a mess in my head, some pages got completely lost and the rest is still a black box. Writing definitely helps me to organize my thoughts. And when it's written, why not share it with someone? I couldn't be the only person tangled up in that particular subject.

It turned out that there's always something to write about. My day job and answering questions on Stack Overflow really help here by continuous chain of ideas and thoughts. As for the frequency, I tried to post regularly but I failed many times and it bothered me. Now I'm perfectly happy with posting when I feel like it as long as it's not just another lousy post pretending regularity.

I originally started posting both here and on dotnetportal but as I saw hundreds of views there and zero here I quickly decided where to put my effort. There's no reason to publish the same article on two different sites when it does not move the ball forward. I few months ago, I realized that with hardly any comments to my posts I no longer care about publicity in the first place and can as well return here. Apart from that, I also decided to write in English in order to be discoverable by the whole world and not just developers from the Czech Republic and Slovakia.

Having the answers on my mind, my goal for the forthcoming year is to start a knowledge base that will remind my of what I have learned and hopefully also help others who seek answers on the internet.