Check if a Float number falls within a range using Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. I was having a conversation with a bunch of C# 2.0 developers the other day who were planning to move to C# 3.0 and then 4.0. They had a requirement to check if a number falls within a specific range and wanted to see how this could be done in 3.0. I said use Extension Methods. Here’s some code that checks if a float number falls within a range, using an Extension Method

C#

static class Program
{
public static void Main(string[] args)
{
float number = 23.5f;
if (number.CheckRange(20.0f, 25.5f))
{
Console.WriteLine("In Range");
}
else
{
Console.WriteLine("Out of Range");
}
Console.ReadLine();
}

static bool CheckRange(this float num, float min, float max)
{
return num > min && num < max;
}
}

VB.NET

Module Module1
Public Sub Main(ByVal args() As String)
Dim number As Single = 23.5F
If number.CheckRange(20.0F, 25.5F) Then
Console.WriteLine("In Range")
Else
Console.WriteLine("Out of Range")
End If
Console.ReadLine()
End Sub

<System.Runtime.CompilerServices.Extension()> _
Private Function CheckRange(ByVal num As Single, _
ByVal min As Single, _
ByVal max As Single) As Boolean
Return
num > min AndAlso num < max
End Function
End Module





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: