Thursday, August 26, 2010

C#: From delegates to anonymous methods to lambda expressions to Func delegates

Let's have a look at how the delegate syntax have evolved since the very first version of the .NET Framework and the C# language until today:
1. Basic delegates, .NET 1.0:

delegate int Add(int number1, int number2);

public int AddNumbers(int number1, int number2)
{
 return number1 + number2;
}

[TestMethod]
public void TestAddNumbers()
{
 var add = new Add(AddNumbers);

 Assert.AreEqual(4, add(1, 3));
}
2. Anonymous methods, .NET 2.0:

delegate int Add(int number1, int number2);

[TestMethod]
public void TestAddNumbers()
{
 Add add = delegate(int number1, int number2)
   {
    return number1 + number2;
   };
   
 Assert.AreEqual(4, add(1, 3));
}
3. Lambda expressions, .NET 3.5:

delegate int Add(int number1, int number2);

[TestMethod]
public void TestAddNumbers()
{
 Add add = (number1, number2) => number1 + number2;

 Assert.AreEqual(4, add(1, 3));
}
4. Func<> delegates, .NET 3.5:

[TestMethod]
public void TestAddNumbers()
{
 Func add = (number1, number2) => number1 + number2;

 Assert.AreEqual(4, add(1, 3));
}
Published: 25.08.2010

Thursday, August 19, 2010

C#: How to get the default value for a type using reflection

The following code snippet gives you the default value for the given type:

public static object GetDefaultValue(Type type)
{
 object value = null;

 if (type.IsValueType)
  value = Activator.CreateInstance(type);
 else
  value = null;

 return value;
}

Friday, August 13, 2010

Focus on good code instead of the latest technology

Ever since the first version of the .NET framework it has allowed us to create good object oriented code. Yet many .NET based applications have already been rewritten numerous times due to poor code and architecture and still the developers are feeling bad about the code quality.

Why is this? I think a major factor is due to the focus on technology, frameworks and tools, which by them self do not lead to good and maintainable code.

Though lately I've noticed a shift in the industry and on the projects that I'm involved in. We are slowly shifting to a more craftsmanship focus, where we value software principles and designs over technology. This has many great benefits for us developers. For years we have had to stay up to date on the latest technology. Today we can learn software principles and designs that have been around since the 70s, and reuse these across technological platforms. Over time this will give us better knowledge and more time to write good, maintainable code instead of spending valuable time learning every new framework out there. Cause today, most frameworks already enable us to create great software.

Thursday, August 12, 2010

C#: How to round up a floating-point number

If you need to round up a floating-point number to the closest integer, then you can use the System.Math.Ceiling method:

System.Math.Ceiling(3.0)  // Returns 3
System.Math.Ceiling(3.4)  // Returns 4
System.Math.Ceiling(3.8)  // Returns 4

Every developer should know SQL

Sooner or later every developer will have to touch a database. Without proper SQL knowledge, the result will be bad performance and bad security. Using an ORM doesn't change the performance part. Unless you know if the generated queries are good or bad, you risk getting a slow application.

I remember one time when helping out a customer who had some performance issues with their help desk application. When they called me, they had 1 300 help desk cases in the database and the performance was terrible. After doing some tracing I found the application to be doing 13 000 database queries on the page that showed all the help desk cases. That's 10 queries per case. When going through the code, I found a for-each loop with lazy loading inside it. After removing the lazy loading and modifying the SQL to use joins, the number of queries went down to 1 and the performance was great.

So how do we reduce the risk of getting issues like this with our software? My advice here is to:
1) Make sure all the team members have some basic knowledge on SQL and how to use a profiling application such as SQL Profiler.
2) Review any data access code and trace the application on a weekly basis.

Saturday, August 7, 2010

How to change an existing Visual Studio project into a test project

If you prefer to have your tests in the same Visual Studio project as the source code you are testing, then in order to be able to run your tests the project must be modified to be a test project. This is how to do it:

1) Choose Add reference on the project, and add a reference to "Microsoft.VisualStudio.QualityTools.UnitTestFramework".

2) Edit the project file by right clicking it and choosing "Unload Project". Then right click again and choose Edit. Notepad can optionally be used for this.

3) In the first <PropertyGroup> section, add the following element:

<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

The first GUID is the project type identifier for a test project, the second is the identifier for a C# class library. If your project is of any other type, replace the second GUID with the correct project type GUID defined here.

4) Save and choose Reload project.

You should now be able to run your tests through Visual Studio.

Think twice before changing to a NOSQL database

For the 15 years or so that I have been involved in the IT industry, the most stable technology around has been relational databases. A SQL Server database created more than 10 years, if modeled properly, is just as good today.

The same cannot be said about most other technologies. Front end technologies for instance, moves faster than ever. Any front end code written today is most likely to be rewritten within a few years time.

An important success factor in a project is to have as few moving, unstable parts as possible. Relational databases have been around for decades with a good track record, while most NOSQL databases on the market are new and immature. I would thus think twice before deciding to use a NOSQL database.

Thursday, August 5, 2010

C#: How to dynamically get or set property values using reflection

Snippet for dynamically getting the value of a property using reflection:


var customer = new Customer();
customer.CustomerId = 3;

var id = customer.GetType().GetProperty("CustomerId").GetValue(customer, null);
// id is 3.

And to set the value of a property:


var customer = new Customer();

customer.GetType().GetProperty("CustomerId").SetValue(customer, 3, null);
// customer.CustomerId is now 3.

C#: How to check if a type has a default/parameterless constructor

The following C# snippet returns true if the passed in type has a default/parameterless constructor:


public bool HasDefaultConstructor(Type type)
{
 if (type.IsValueType)
  return true;

 var constructor = type.GetConstructor(Type.EmptyTypes);

 if (constructor == null)
  return false;

 return true;
}

C#: How to get all the classes that inherits from a specific type

Code snippet for getting all the classes that inherits from a specific type:

public IList GetAllDerivedClasses(Type baseType)
{
 return baseType.Assembly.GetTypes().Where(
  x => 
   x.IsClass
   && x.IsSubclassOf(baseType)).ToList();
}

Wednesday, August 4, 2010

Don't implement things you dont need

In most of the projects that I have been involved with over the years, the users have requested different type of functionality which seemed critical at the time. But after it was implemented it has not been used. This feels annoying to us developers. However before criticizing others we should look at ourselves first. How often is it not that we implemented code with unnecessary complex abstractions? Very often.