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.