Extension Methods

Using extension methods

With framework 3.0 we can use extension methods. Extension methods allow you to add methods to existing types. Therefore you just have to create a static class and a static method with the this keyword in the parameters and after this the type on which you want the extension. Something like this

        public static bool IsImage(this string fileName)
            bool returnvalue = false;
            if(ImageFunctions.ImageFormats().ContainsKey (Path.GetExtension (fileName)))
                returnvalue =true;
            return returnvalue ;

In the example above there were a lot of filenames in a grid and only with the files which actually is image has to be send to a webservice. ImageFormats in this case is a readonly collecton with supported image extensions. It's going to look like this:

foreach (DataGridViewRow datagridviewrow in datagridview.Rows)
              string file = (string)datagridviewrow.Cells[1].Value;
                //upload to webservice

Unit test the extension method

Well that's easy in this case, put an string in the resources of you project with an extension from an image:

        public void IsImageTest()
            string fileName =ResizeImagesTest.Properties.Resources.TestImageString;
            bool expected = true; 
            bool actual;
            actual = StringExtensions.IsImage(fileName);
            Assert.AreEqual(expected, actual);




Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!