Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

February 23, 2015

Get info about your machine

Today’s article is about a static class from .NET Framework which provides some information about your machine and platform used – System.Environment. I find this class immensely useful only for some very specific tasks, because not every application could benefit from what it provides. I’ll discuss only few of its public members, because it’s quite well documented on MSDN.

CurrentDirectory

I use this when I need to know a full path of a configuration file or any other resource file on a disk in case I placed it in the same folder as my application binaries are placed.

var path = Path.Combine(Environment.CurrentDirectory, "config.xml");

But there’s one catch, this does not work with Windows services, because when they are started by a system, their default working directory is in C:\Windows\System32 since Service Control Manager is placed there. So if you are not sure if your code will run from a Windows service, it’s safer to use something like as follows.

Path.GetDirectory(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

MachineName


No need to describe, I just want to point it out, because I use it a client or server identifier in a network communication.


UserInteractive


This one is not really self-explanatory and can be easily overlooked, but I place it among my best findings in .NET Framework. Have you ever tried to debug a Windows Service? Right, not a very pleasant business. This could make a whole nother article, so here’s a random example for now, maybe I’ll do one later myself.


GetCommandLineArgs()


You probably know how to access command line arguments from a console application, but how to access then from a WinForms app or a class library? That’s where Environment.GetCommandLineArgs() shines. Just know that the first arguments is always a path to the executing assembly or just its name, it depends where a working directory is.


GetFolderPath(Environment.SpecialFolder)


An easy way to get paths to many special system folders like Desktop, MyDocuments or Program Files.

February 16, 2015

Concurrency in C# Cookbook review

book cover
Concurrency is a topic that many programmers, even some senior ones, still didn't get right. These days, it's mostly misconceptions about asynchronous programming, but apart from that, not many people heard about reactive programming (Rx) or used TPL Dataflow.

What I like about the book is that it covers all different types of concurrency and clearly explains when would you use one in favor of the other. It's also easy to skip what you already know thanks to its cookbook format.

Follows a short extract from the first chapter "Concurrency: An Overview" that is in my opinion a very good start to this topic and every single programmer should know even if he/she don't use it.

Concurrency
    Doing more than one thing at a time.
Multithreading
    A form of concurrency that uses multiple threads of execution.
Parallel Processing
    Doing lots of work by dividing it up among multiple threads that run concurrently.
Asynchronous Programming
    A form of concurrency that uses futures or callbacks to avoid unnecessary threads.
Reactive Programming
    A declarative style of programming where the application reacts to events.

The book is all about introducing you to all these topics by providing you with short and clean code samples with explanations. Then there are chapters that describe how to test concurrent code, how to interop between different styles, how it fits into OOP world and few other. Amongst them, I particularly enjoyed a chapter called "Collections" which describes various types of concurrency-friendly collections. Have you heard about immutable or blocking collections yet? I certainly had not before I read the book. Now I even know which one to choose when dealing with concurrency in my code.

I recommend this book to everyone who had not chance to use threading much to get a nice high-level view on concurrency, but also to everyone who started with threads in early .NET Framework versions and still use it these days. Basically, you should not need to call new Thread(); in your code anymore.

Head to the author's blog for more.

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 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.