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


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

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


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")
Console.WriteLine("Out of Range")
End If
End Sub

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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: