November 4, 2009

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


'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Check if a Float number falls within a range using Extension Methods"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions