Dynamic Programming in C# 4.0 – An Overview

One of the most interesting additions to C# 4.0, I think, is the dynamic addition. Just thinking about this makes me excited. I will jump right into a little theory then some code.

The Theory of Dynamic

So what is this here dynamic thingy? dynamic in C# 4.0 refers to dynamic binding and dynamic binding is what happens at runtime and not at compile time. This involves binding a method, property, operator, member etc of an object at runtime. Yes I know this sounds like polymorphism or like the var keyword or even like using the ultimate base class in C# – object. First and foremost you have to let go or what you know and remember this important fact.

dynamic != var && dynamic != object

The keyword dynamic, casually speaking, tells the compiler that “Even though it cannot resolve the member statically, it should trust the programmer and don’t worry because it will/may be resolved at runtime.”

Code

Here is a sample on how you use the dynamic keyword:

dynamic dyn = “My first time”;
Console.WriteLine(dyn);

Now let’s look at some similarities and differences of var, object, and dynamic for a sec.

var v = 1; // here the compiler will figure out (at compile time) the type for v which will be int.
Console.WriteLine(v.GetType().ToString());
//v.Compute(); // causes a compiler error
object o = 1; // this is boxed from value type to an object with type being int32
Console.WriteLine(o.GetType().ToString());
//o.Compute(); //also gives a compiler error
dynamic d = 1; //type here is int32
Console.WriteLine(d.GetType().ToString());
d.Compute(); // does not give compile time error but will throw a runtime RuntimeBinderException

Continue reading

Advertisements
Threading with the Thread Pool and BackgroundWorker

Threading with the Thread Pool and BackgroundWorker

threadsToday I want to talk about threads since every programmer works with them and absolutely loves them. Typically, when we create a thread, your code can look like this:

static void Main(string[] args)
{
TraditionalThreadCreation();
Console.Read();
}

static void TraditionalThreadCreation()
{
// Create threads
Thread thread1 = new Thread(Task);
Thread thread2 = new Thread(Task);

// this guy will do even numbers
thread1.Start(0);
// this guy will do odd numbers
thread2.Start(1);
//wait for first thread to finish
thread2.Join();
}

static void Task(object p)
{
for (int i = int.Parse(p.ToString()); i <=10; i += 2)
Console.WriteLine(i);
}

There is nothing wrong with creating threads like the code above. But there is one thing you have to keep in mind. Thread creation and startup has overhead. A typical thread can take up 1MB of your precious memory. Shocked?? Well you are not alone. Continue reading

MVVM (Model View View-Model) For Dummies/Simplified

Introduction

A few months ago I took the leap from WinForms programming to WPF and quite naturally, I took to it like a duck to water. Well, to be honest I had been developing Silverlight applications since its inception and being that Silverlight is a subset of WPF it required a low learning curve to catch on. However, the concept of Commanding was a bit different in WPF and I soon began to see how much more powerful Commanding in WPF was compared to Silverlight.

One of the areas in which Commanding is exemplary is in the way in which it complements MVVM.  But what is MVVM, and why is it useful? This is the toughest concept (In my opinion) to grasp when it comes to WPF (and Silverlight) programming. Why you ask? Because it is simple and as developers we often like code or concepts that warp our minds, so when we figure it out we can brag to our peers how it only took 2 hours to understand and implement the next BIG thing (No I am not projecting).  On a side not, I have found that everyone one who blogs about MVVM complicate it by adding too much code which just throws you for a loop. Simplicity is the key to all things complicated. So let’s delve into a little theory and we will finish up with some short-to-the-point code.

Purpose

The purpose of this post is to

a. Give a simple and clear definition of Model View View-Model

b. Provide a clear and simple sample that clearly illustrates MVVM usage

MVVM?

Figure 1.

MVVM - Model View ViewModel

MVVM - Model View ViewModel

Just in case you cannot read the text in the image here it is below:

  1. The View holds a reference to the ViewModel. The View basically displays stuff by Binding to entities in the View Model.
  2. The ViewModel exposes Commands, Notifiable Properties, and Observable Collections to the View. The View Binds to these ViewModel entities/members
  3. The Model is your data and or application objects that move data while applying Application Logic. If you have a Business Layer then you might not need this.

Above is a simple figure that tells you exactly what MVVM is. In my own words, the ViewModel is the most significant in the entire pattern as it is the glue that sits between the View and the Model and binds both of them together. Now let’s explore some code. Continue reading

WPF Commanding

WPF Commanding: The Basics

Commanding in WPF is unlike your traditional events in Winforms. Commands were primarily designed to be used at the application level, but they have become one of the most popular features among developers when it comes to UI programming (we tend to use them more than they should be). Commands enable the developer to define a task once and “attach” it multiple times without having to go through the traditional means which would require duplicating the code or even calling it in more than one place (This is the magic). WPF intrinsically provides 5 commands that you can use out of the box.

  1. ApplicationCommands
  2. ComponentCommands
  3. EditingCommands
  4. MediaCommands
  5. NavigationCommands

Continue reading

Simple Tips To Help You Write Friendlier Code

Clean Code.

To paraphrase BJarne Stroustrop, Clean Code is elegant, simple and efficient and does one thing well. I particularly love this statement because it has always been a strong belief of mine. I will now attempt to go through a few simple every day checklist that can improve code readability and ultimately, maintainability.  

Tip #1: Identifiers

Identifiers, functions, classes/interface, should have names that are clear and concise. Most developers, including myself, love to write code late at night. This is when we can crank out our latest and greatest. But if you are like me, when you look at that same piece of art you cranked out a few weeks ago (or even the night before), you can hardly recognize what the variable call killSwitchForCat means. 

Below is a table of good and bad identifiers just to give an idea.

Bad Good
int w = dayOfMonth/7; // what is ‘w’ in the equation int week = dayOfMonth/7;  //Write what was intended
int l; // don’t know if this is 1 or lowercase L int length; // This is more easily identified and is even more searchable in Visual Studio
   

  Continue reading

Another Code Blog!!

 

Hi, this is another blog about coding in the .Net Framework. Why another blog you might ask? Well I love learning and I even though I may read a lot, I only seem to remember about 60% of what I read.

If you are a fan of the .Net Framework you will agree that it requires a lot of effort to keep up with the many Microsoft releases. For example, Silverlight is now in Beta 4 and I haven’t even mastered Silverlight 3.0. The Microsoft community releases a lot of tools that can simplify development yet many like me only seem to know of them when you step into an interview or in a blog where the author assumes that you know the tool and flashes around the acronym.

The primary aim of this blog is to post simple code samples that demonstrate how to get the job done with minimal effort. I am not a writer so don’t expect to see award winning writing here. I will do my best to explain language features, methodologies, patterns and practices, etc. in the most basic of words in hopes that YOU will provide valuable feedback.