tags:

views:

110

answers:

4

I have the following code, where ApplicationType is an enum. I have the same repeated code (everything except the parameter types) on many other enums. Whats the best way to consolidate this code?

 private static string GetSelected(ApplicationType type_, ApplicationType checkedType_)
    {
        if (type_ == checkedType_)
        {
            return " selected ";
        }
        else
        {
            return "";
        }
    }
+2  A: 
Kevin Montrose
*Constraint cannot be special class 'System.Enum'*
Matthew Scharley
You would need to use the keyword "struct" because an enum won't work. You can do further type checking at runtime to ensure that it is infact an enum.
Josh
This is **massively** overkill...
Marc Gravell
A: 

It's hard to do this through a generic constraint at compile time because an enum is really an int. You'll need to restrict the values at runtime.

Jeremy McGee
A C# enum is *usually* an `int`, actually.
Marc Gravell
Whups, the latest project I've been working on maps enums to a byte in the database - confused. I'll update the answer. Thanks!
Jeremy McGee
A: 

For equality on an emum? Simply:

public static string GetSelected<T>(T x, T y) {
    return EqualityComparer<T>.Default.Equals(x,y) ? " selected " : "";
}

You could add where T : struct to the top line, but there isn't a need to do that.

For a full example including demo:

using System;
using System.Collections.Generic;
static class Program {
    static void Main() {
        ApplicationType value = ApplicationType.B;
        Console.WriteLine("A: " + GetSelected(value, ApplicationType.A));
        Console.WriteLine("B: " + GetSelected(value, ApplicationType.B));
        Console.WriteLine("C: " + GetSelected(value, ApplicationType.C));
    }
    private static string GetSelected<T>(T x, T y) {
        return EqualityComparer<T>.Default.Equals(x, y) ? " selected " : "";
    }
    enum ApplicationType { A, B, C }
}
Marc Gravell
A: 

Is this appropriate for your needs?

private static string GetSelected<T>(T type_, T checkedType_)
    where T: struct
{
    if(type_.Equals(checkedType_))
        return " selected ";
    return "";
}
Programming Hero