March 9, 2010

C# 4.0: Named Parameters

C# 4.0: Named Parameters : C# introduces Named parameters. While calling a method, name: value pair syntax can be used for the parameters. Order doesn't matter. As you might guess, Named parameters can't precede optional parameters. I wrote few tests to understand these concepts.
You need VS2010, and NUnit if you want to try this code as is on your machine.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace LearningCSharp40
{
    public class Division
    {
        public int Divide(int dividend, int divisor)
        {
            return dividend / divisor;
        }
    }
    [TestFixture]
    public class LearnNamedParameters
    {
        Division division = new Division();
        private int quotientFromPositional = 0;
            
        [SetUp]
        public void Setup()
        {
            quotientFromPositional = division.Divide(20, 10); // positional
        }

        [Test]
        public void  QuotientShouldbeSameWhenCalledWithNamedParameters()
        {
            int quotientWithNamedParams = division.Divide(dividend: 20, divisor: 10); // named parameters
            Assert.AreEqual(quotientFromPositional, quotientWithNamedParams, 
                            "quotient should be 2 even with named parameters");
       
        }
        
        [Test]
        public void NamedParametersInDifferentOrder()
        {
            int quotientWithNamedParamsInDifferentOrder = division.Divide( dividend:20,divisor:10); // Order is different
            Assert.AreEqual(quotientFromPositional, quotientWithNamedParamsInDifferentOrder, 
                            "quotient should be same even called with named paratmeters in different parameter");
        }

       
        [Test]
        public void QuotientShouldBeSameWhenMixOfPositionalAndNamedApproachIsUsed()
        {
            int quotient = division.Divide( 20, divisor: 10); 
            Assert.AreEqual(quotientFromPositional, quotient,
                            "quotient should be same even with mix of positional, and named parameters");

        }
        [Test]
        [Ignore]
        public void NamedParametersCantProcedePosition_CompilerError()
        {
            Division division = new Division();
            //Uncomment to see the compiler error...
            // int quotient = division.Divide( dividend: 20,10); // named parameters cannot procede positional
            // Assert.AreEqual(2, quotient, "quotient should be 2 even with named parameters");
        }

        [Test]
        [Ignore]
        public void NamedParameterSpecifiesAParameterForWhichAPositionalArgumentHasAlreadyGiven_CompilerError()
        {
            Division division = new Division();
            //Uncomment to see the compiler error...
           // int quotient = division.Divide( 20,dividend:20); 
        }
    }
}