I’ve been playing around with delegates and lambda expressions, and thought I would note down what I had learned (this is a programming notebook, after all).

    class Program
    {
        delegate int IntFunc(int a, int b);

        static void Main(string[] args)
        {
            IntFunc add = new IntFunc(delegate(int a, int b) { return a + b; });
            Console.WriteLine(add(1, 2));
        }
    }

I am particularly interested in how we can improve the following line with lambda expressions and a little syntactic sugar:

IntFunc add = new IntFunc(delegate(int a, int b) { return a + b; });

So, let’s start by turning it into a lambda-expression:

IntFunc add = new IntFunc((a, b) => { return a + b; });

Here, we say “parameters a and b of our deletegate ‘go to’ (=>) our block of functionality, which is defined in the {} braces.

But we don’t actually need the curly braces, or the return for that matter, as the lambda expression will infer this. So, we can reduce the expression down to the following:

IntFunc add = new IntFunc((a, b) => a + b);

However, looking at the original statement, we realise that the new IntFunc isn’t necessary either. It could have read:

IntFunc add = delegate(int a, int b) { return a + b; };

So, our lambda expression reduces down even further:

IntFunc add = (a, b) => a + b;

Marvellous! It also explains to me quite nicely how lambda expressions syntax derives from the equivalent delegate syntax.

But, we’ve not finished here. Take our delegate type:

delegate int IntFunc(int a, int b);

C# already has an in-built type func<> to save us from such declarations. We can dispense with the delegate line completely when we recognise that we have two inputs of type int and one output of type int.

Our final class looks like this

    class Program
    {
        static void Main(string[] args)
        {
            Func add = (a,b) => a + b;
            Console.WriteLine(add(1, 2));
        }
    }

Lovely!

, , ,

I was presented with a scenario recently which I felt an ideal opportunity to begin my adventures into LINQ.

Essentially I had to parse a collection setting a property in objects within the collection based on a condition.

The requirement is more obvious when presented in its standard iterative solution:

//standard iteration
foreach (LogFileDataItem lfd in logFileData)
{
    if (lfd.FileName.Equals(currentLine, StringComparison.OrdinalIgnoreCase))
    {
        lfd.SQLScriptExecuted = true;
    }
}

Quite simple really.

So how would we express this in LINQ? Well, the following ought to suffice:

IEnumerable retrievedScripts;
retrievedScripts = from logFileDataItem in logFileData
                   where logFileDataItem.FileName.Equals(currentLine)
                   select logFileDataItem;

foreach (LogFileDataItem lfd in retrievedScripts)
{
    lfd.SQLScriptExecuted = true;
}

However, the above is more verbose than its predecessor, so we can refactor, removing the IEnumerable retrievedScripts variable:

foreach (LogFileDataItem lfd in
         from logFileDataItem in logFileData
         where logFileDataItem.FileName.Equals(currentLine)
         select logFileDataItem)
{
    lfd.SQLScriptExecuted = true;
}

Ahhh, but wait, aren’t Lambda Expressions even more concise? Well, yes, so here it is in Lambda Expressions:

//can be expressed in lambda expressions as:
foreach (LogFileDataItem lfd in logFileData.Where(item => item.FileName.Equals(currentLine)
                                           .Select(item => item))
{
    lfd.SQLScriptExecuted = true;
}

But which is best? Time to consult Stackoverflow?

Well, for starters, the .Select(item => item) is totally useless. So, happy days! More refactoring:

foreach (LogFileDataItem lfd in logFileData.Where(item => item.FileName.Equals(currentLine)))
{
    lfd.SQLScriptExecuted = true;
}

And John Skeet (no less!) recommends we actually move the where clause out. Who am I to argue?

IEnumerable lines = logFileData.Where(item => item.FileName.Equals(currentLine));
foreach (LogFileDataItem lfd in lines)
{
    lfd.SQLScriptExecuted = true;
}

And as for their relative differences? Well, not much as it would appear. It’s really just a matter of personal preference.

, , , ,

Hmmmm, I like Field Initialisers in C#, but I also like Constructor Initialisers in C#. But which is better? There’s only one way to find out…FIGHT!

Well, actually, no. Here is some C# code to compare them. I was interested as to what fired first:

    //This is the class we will use to test field vs constructor initialisers
    //Write out to the console when the constructor is called.
    class FieldInitTest
    {
        public FieldInitTest(string number)
        {
            Console.WriteLine(number);
        }
    }

    //This class will perform our field vs constructor initialiser test
    class FieldInitTester
    {
        public FieldInitTest fieldInitTest1;
        public FieldInitTest fieldInitTest2 = new FieldInitTest("2");
        public FieldInitTester()
        {
            fieldInitTest1 = new FieldInitTest("1");
        }
    }

    //run the test
    static void Main(string[] args)
    {
        FieldInitTester fit = new FieldInitTester();
    }

When run, the output is shown below:

Field and Constructor Initialiser - Results

So there we have it, field initialisers are run before constructor ones. As to which is better…I’ll leave that up to you.

, , ,

Fantastic! I’ve been grappling with WordPress’ TinyMCE WYSIWYG editor for two months now, and have grown to dread having to present code within this tool. I even took to performing the syntax highlighting myself, and that meant manually colouring text according to how it appeared in my IDE.

So, I decided to call in the help of a syntax highlighter, and settled upon across Alex Gorbatchev’s SyntaxHighlighter.

So here is the first bit of code (in C#) that I’ve tested out. It’s fairly trivial, and does nothing meaningful. It doesn’t, of course, recognise any of the built-in C# class names, but that would be expecting a hell of a lot!

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        textBox1.Focus();
        MyKeyPress mkp = new MyKeyPress();
        mkp.KeyPress();
    }
 }

Of course, if you are reading this through a feed, then you’ll not see any of this. So, Just follow the link!

If it’s not too onerous, I may revisit some of my other posts.

, ,

Programmers like new toys that they can play with, be it a second monitor, a new IDE, or a new programming language. They also like to feel that they are learning new things and not getting assigned to the technological scrap-heap and so will inherently favour (for example) C#3 above VB6 even when the final solution might be suboptimal.C#

I found myself drifting into this mindset recently when prototyping a design for component to fit in with an existing framework of COM components.

The component needed to call out to SQL Server 2005 to start an Agent Job. My first instinct was that I had to interface with SQL 2005 Native Client components through the .NET libraries. I envisaged something something like this:

//...get the connectionString somehow...
string connectionString = "Data Source=SOMESERVER;Initial Catalog=SomeDatabase;Integrated Security=SSPI;Provider=SQLNCLI.1;";
OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
ServerConnection serverConnection = new ServerConnection(oleDbConnection.DataSource);
Server oSqlServer = new Server(serverConnection);

JobServer oAgent = oSqlServer.JobServer;
Job oJob = oAgent.Jobs["Test"];
JobHistoryFilter oFilter = new JobHistoryFilter();
oFilter.JobName = "Test";
oJob.Start();

…or something similar therein.

The component would have to expose a COM Interface and be registered using REGASM, which would requrie manual intervension in the shipping process.

In addition to this, I would have neededed to organise for the SQL 2005 Client tools installed on four servers and undertake regression testing of the applications on these servers to inspire confidence that this hadn’t broken anything.

To be frank, it all seemed a little onerous and overcomplicated. Apart from simply wanting to use C#, the reason for this doing this vb6was based on an assumption that I needed the .NET library code to hook into SQL Server and that there was no other way. Really? Have you ever heard such nonsense?

Without realising, I’d very nearly falling into the Second System Effect trap (of sorts). All I really had to do was make a call out to the SQL Server sp_start_job to achieve the same effect, and all I needed was trusty old MDAC 2.8. This meant I could write it in VB6 to fit in with existing framework components with none of the impact or complication inherent with the C#-developed component.

So, I set about writing a little test application as proof of concept. It looked something like this:

Private Sub Command1_Click()
    Dim connection As New ADODB.Connection
    Dim connectionString As String

    connectionString = "Data Source=SOMESERVER;Initial Catalog=SomeDatabase;Integrated Security=SSPI;Provider=SQLOLEDB.1;"

    Call connection.Open(connectionString)

    connection.Execute ("EXEC msdb.dbo.sp_start_job @job_name=N'Test'")

    MsgBox ("Success")
End Sub

But I really wanted to use C#! However,  in this instance it just wasn’t feasible.

So, in conclusion, don’t get blinded by shiny new toys or by a desire to improve oneself, don’t simply dive into the first solution that you come across, and remember, complication is ruination!

, , ,

Most C# (and C, C++, Java and JavaScript developers for that matter) will be aware of the default keyword and its usage in the switch statement:


switch (options)
{
    case 1:
        {
            //do something
            break;
        }
    default:
        {
            //do something
            break;
        }
}

But it also has an additional use in C# in conjunction with Generics and types. Each type in C# has a default value. Value Types have a default value of zero (false for boolean) and reference types have a default type of null We can try a simple example:

int i = default(int); //i is initialised to zero

And then try it in conjunction with Generics:

class DefaultTest<T>

{
    public DefaultTest()
    {
        System.Console.WriteLine("Default for '" + typeof(T) + "' is " + default(T));
    }
}

class Program 
{
    static void Main(string[] args)
    { 
        DefaultTest<bool> b = new DefaultTest<bool>();      //outputs 'false'
        DefaultTest<int> i = new DefaultTest<int>();        //outputs '0'
        DefaultTest<string> s = new DefaultTest<string>();  //outputs nothing
        DefaultTest<String> S = new DefaultTest<String>();  //outputs nothing
        DefaultTest<double> d = new DefaultTest<double>();  //outputs 0
    }
}

You can read some more on these in this article: http://en.csharp-online.net/Understanding_Generics—The_default_Keyword_in_Generic_Code

,

Here’s an idea of something to try when you’re trying to learn about C# and the .NET framework classes.

When using a type, why not include its namespace in your code as as well. For example:

//without namespace
OleDbConnection oleDbConnection = new OleDbConnection(connectionString);

//with namespace
System.Data.OleDb.OleDbConnection oleDbConnection = new System.Data.OleDb.OleDbConnection(connectionString);


I’m not necessarily advocating this for use when writing production or live apps (it is a bit wordy, but i’m undecided about that at the moment), however when you’re hacking about and learning new stuff, it may be advantageous for your learning experience if you include the full namespace declaration; hopefully this will help you remember the association between libraries, namespaces and classes.

Just a thought. Take it or leave it…

,

Before .NET 4.0 there was no explicit method to clear a C# StringBuilder object.

We had to resort to one of three approaches:

1. Remove from the start of the StringBuilder by its length:

    myStringBuilder.Remove(0, myStringBuilder.Length);

2. Store the contents in another string and call Replace upon the stringbuilder using the string as a parameter:

    string s = myStringBuilder.ToString();
    myStringBuilder.Replace(s, "");

3. Or simply just set the Length property to zero. This property is not read-only.

    myStringBuilder.Length = 0;

But which is the fastest? Crude (and in no way scientific) tests on my laptop at home gave the following results when looping round this operation 50 million times. All numers are in milliseconds:

1. 5585,    5601,     6037
2. 14945,   14679,    15094
3. 4898,    4805,     5023

So there we have it. Setting the Length directly was the best

C# .NET 4.0

But all this is immaterial if you are using C# .NET 4.0, as Microsoft have kindly extended the StringBuilder obect to include this method:

http://blogs.msdn.com/wriju/archive/2010/03/01/net-framework-4-0-newbie-stringbuilder-new.aspx

But what of its relative performance?

5772,   5476,   5226

So, it would seem from my crude and unscientific tests that for C# 4, the quickest way to clear a StringBuilder object is actually avoid the inbuilt clear method, and set the length directly to zero.

I’ve put the sample code here so that you can test it for yourself:

ClearStringBuilder.cs

,