Optional Parameters and Named Arguments in Framework 4

This time I will demonstrate another nice feature in the framework 4
C # 4.0 now supports using Optional Parameters with Methods, Constructors, and Indexers.

Earlier versions of the framework, create a mountain default variable is actually needs to create two methods.

 private static double GetPriceIncludesVAT(double p, double vat)
 {
     return p * vat;
 }
 private static double GetPriceIncludesVAT(double p)
 {
     return GetPriceIncludesVAT(p, 16.5);
 }


Today, with the framework 4, C #, we can give a default (like VB) to methods.


Another nice thing we got, it Named Arguments.
So that the code will organized - we can be the names in a methods call.
Look for the following example:

 double priceWith15VAT = GetPriceIncludesVAT(vat: 15, p: 50);

Here is the Code:

using System;
namespace OptionalParm
{
    class Program
    {
        static void Main(string[] args)
        {
            double priceDefult = GetPriceIncludesVAT(50.0);
            Console.WriteLine("Price with 16.5% VAT (defult value) of 50 is: " + priceDefult);
            double priceWith17VAT = GetPriceIncludesVAT(50.0,17);
            Console.WriteLine("Price with 17% VAT of 50 is: " + priceWith17VAT);
            double priceWith15VAT = GetPriceIncludesVAT(vat: 15, p: 50);
            Console.WriteLine("Price with 15% VAT of 50 is: " + priceWith15VAT);
            Console.ReadKey();
        }
        private static double GetPriceIncludesVAT(double p,double vat = 16.5)
        {
            return p * vat;
        }
     }
} 

The Result:

Other examples of  framework 4:
Yours,
Roi

Comments

Popular posts from this blog

A sharepoint list view of the current month

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters

Export SharePoint 2010 List to Excel with PowerShell