C# 101: Extension Method Creation For Variables and Enums

Class101 With the advent of C# 3.0 in .Net 3.5 one can create extension methods for common tasks for any existing types and enums which one finds in their code. This is a quick how-to article which provides those two examples using an integer and a user defined enum.

Basic Extension Example

Sometimes one needs to know when an integer value is negative. Here is an extension method to do that and its usage example.

public static class MyExtensions
{
    public static bool IsNegative( this int value )
    {
        return (value < 0) ? true : false;
    }
}
  1. Step one create a static class.
  2. Create a static method return type can vary to suit the target operations needs.
  3. Use the this keyword in the input parameters of the type which the extension will be used by.

In the above case we want integers to report if they are negative or not. Here is the usage:

int value = 1;

Console.WriteLine( value + " is " + value.IsNegative() );
value = --value;

Console.WriteLine( value + " is " + value.IsNegative() );

value = --value;
Console.WriteLine( value + " is " + value.IsNegative() );

/* Output
1 is False
0 is False
-1 is True
*/

Enum Example

Enums can have extensions in C# as well and are very functional.

This example is similar to the previous but we will deal with software development states. The first two states are test related and we will create an extension to determine if the state is in test or not.

public enum States { Test, UserAcceptance, Development, Production, Maintainence };

public static class MyExtensions
{
    public static bool IsInTest( this States state )
    {
        return state < States.LastTestState;
    }

}

So every state before Development is considered a “Testing” state. Here is its usage:

States current = States.Test;
Console.WriteLine("State: " + current + " is " + current.IsInTest());

current = States.Development;
Console.WriteLine( "State: " + current + " is " + current.IsInTest() );

/* Output:
State: Test is True
State: Development is False
*/

HTH

HTH

Share

Leave a Reply