Alan Alan - 8 days ago 6
C# Question

How can I make a method that takes more than one Enum type instead of me having to Cast all the time

I have these method calls and more and this method:

App.DB.UpdateSetting("TimeInterval", (int)Time.UserInput );
App.DB.UpdateSetting("ThemeColor", (int)Theme.Light );

public void UpdateSetting(string setting, int value, string text="" )
{
lock (locker)
{
db2.Execute("UPDATE Setting SET Value = ?, Text = ?" +
" WHERE SettingType = ?", value, text, setting);
}
}


What I would like to do is to be able to avoid typing all those settings to (int). Is there some way I could do that?

Answer

You can use Enum instead of int. That allows you to pass any enum value you ike. The only change you need to make then is to convert the enum to an int inside your method:

public void UpdateSetting(string setting, Enum value, string text = "")
{
    var intValue = Convert.ToInt32(value);

    lock (locker)
    {
        db2.Execute("UPDATE Setting SET Value = ?, Text = ?" +
                      " WHERE SettingType = ?", intValue, text, setting);
    }
}

Now you can call it like this:

App.DB.UpdateSetting("TimeInterval", Time.UserInput );
App.DB.UpdateSetting("ThemeColor", Theme.Light );
Comments