logo
down
shadow

Switch on enum with Flags


Switch on enum with Flags

By : user2948325
Date : November 14 2020, 04:51 PM
it helps some times Declare all these combinations in a switch. (as you started)
Its clear, understandable, maintainable.
code :


Share : facebook icon twitter icon
Switch on Enum (with Flags attribute) without declaring every possible combination?

Switch on Enum (with Flags attribute) without declaring every possible combination?


By : Diana Horecna
Date : March 29 2020, 07:55 AM
it fixes the issue How about this. Of course the arguments and return types of DoSomething, etc., can be anything you like.
code :
class Program
{
    [Flags]
    public enum CheckType
    {
        Form = 1,
        QueryString = 2,
        TempData = 4,
    }

    private static bool DoSomething(IEnumerable cln)
    {
        Console.WriteLine("DoSomething");
        return true;
    }

    private static bool DoSomethingElse(IEnumerable cln)
    {
        Console.WriteLine("DoSomethingElse");
        return true;
    }

    private static bool DoWhatever(IEnumerable cln)
    {
        Console.WriteLine("DoWhatever");
        return true;
    }

    static void Main(string[] args)
    {
        var theCheckType = CheckType.QueryString | CheckType.TempData;
        var checkTypeValues = Enum.GetValues(typeof(CheckType));
        foreach (CheckType value in checkTypeValues)
        {
            if ((theCheckType & value) == value)
            {
                switch (value)
                {
                    case CheckType.Form:
                        DoSomething(null);
                        break;
                    case CheckType.QueryString:
                        DoSomethingElse(null);
                        break;
                    case CheckType.TempData:
                        DoWhatever(null);
                        break;
                }
            }
        }
    }
}
Unexpected behavior between [Flags] enum : long vs [Flags] enum : ulong

Unexpected behavior between [Flags] enum : long vs [Flags] enum : ulong


By : 王李荣
Date : March 29 2020, 07:55 AM
To fix this issue Note that 1 << 63 isn't a ulong or even a long. The compiler interprets it as an int. Observe the following example:
code :
enum TransactionData : long
{
    None = 0,
    Color1 = 1 << 31,
    Color2 = 1 << 63,
}

Console.WriteLine(TransactionData.Color1 == TransactionData.Color2); // True
enum TransactionData : ulong
{
    None = 0,
    Color1 = 1ul << 63,
}
How do I convert an enum between (string, list of flags, enum with flags)?

How do I convert an enum between (string, list of flags, enum with flags)?


By : charmanderson
Date : March 29 2020, 07:55 AM
it fixes the issue Update 2
there is a library that implements most of the functionality you would need from enums, with better performance https://github.com/TylerBrinkley/Enums.NET
code :
ModifierKeys mk = ModifierKeys.None | ModifierKeys.Alt | ModifierKeys.Shift | ModifierKeys.Control;
mk.Tostring();
// Way 1:
ModifierKeys outenum;
bool successful = Enum.TryParse("None,Alt,Control,Shift", out outenum);

Console.WriteLine($"Is Successful ? : {successful}, result : {outenum.ToString()}");
// Way 2:
ModifierKeys outenum = (ModifierKeys)Enum.Parse(typeof(ModifierKeys), "None,Alt,Control,Shift", true);
Console.WriteLine(outenum.ToString());
        ModifierKeys mk = ModifierKeys.None | ModifierKeys.Alt | ModifierKeys.Shift | ModifierKeys.Control;
        List<ModifierKeys> mklist =
            mk
            .ToString() // Convert the enum to string
            .Split(new[] { "," } , StringSplitOptions.RemoveEmptyEntries) // Converts the string to Enumerable of string
            .Select(//converts each element of the list to an enum, and makes an Enumerable out of the newly-converted items
                strenum =>
                {
                    ModifierKeys outenum;
                    Enum.TryParse(strenum , out outenum);
                    return outenum;
                })
            .ToList(); // Creates a List from the Enumerable
 ModifierKeys[] mk = {ModifierKeys.None, ModifierKeys.Alt, ModifierKeys.Control, ModifierKeys.Shift};
 ModifierKeys mkc = mk.Aggregate((prev, next) => prev | next);
 Console.WriteLine(mkc.ToString());
    string[] mk = {"None", "Alt", "Control", "Shift"};
    ModifierKeys mkc = mk.Select(x => {ModifierKeys outenum; Enum.TryParse(x, out outenum); return outenum;}).Aggregate((prev , next) => prev | next);
    Console.WriteLine(mkc.ToString());
public class EnumConverter<T> where T : struct, IConvertible, IFormattable
{
    private Type EnumType { get; set; }

    public Type UnderlyingType
    {
        get
        {
            return Enum.GetUnderlyingType(EnumType);
        }
    }
    public EnumConverter()
    {
        if (typeof(T).IsEnum)
            EnumType = typeof(T);
        else
            throw new ArgumentException("Provided type must be an enum");
    }
    public IEnumerable<T> ToFlagsList(T FromSingleEnum)
    {
        return FromSingleEnum.ToString()
        .Split(new[] { "," } , StringSplitOptions.RemoveEmptyEntries)
        .Select(
            strenum =>
            {
                T outenum = default(T);
                Enum.TryParse(strenum , true , out outenum);
                return outenum;
            });
    }
    public IEnumerable<T> ToFlagsList(IEnumerable<string> FromStringEnumList)
    {
        return FromStringEnumList
        .Select(
            strenum =>
            {
                T outenum = default(T);
                Enum.TryParse(strenum , true , out outenum);
                return outenum;
            });
    }

    public T ToEnum(string FromString)
    {
        T outenum = default(T);
        Enum.TryParse(FromString , true , out outenum);
        return outenum;
    }
    public T ToEnum(IEnumerable<T> FromListOfEnums)
    {
        var provider = new NumberFormatInfo();
        var intlist = FromListOfEnums.Select(x => x.ToInt32(provider));
        var aggregatedint = intlist.Aggregate((prev , next) => prev | next);
        return (T)Enum.ToObject(EnumType , aggregatedint);
    }
    public T ToEnum(IEnumerable<string> FromListOfString)
    {
        var enumlist = FromListOfString.Select(x =>
        {
            T outenum = default(T);
            Enum.TryParse(x , true , out outenum);
            return outenum;
        });
        return ToEnum(enumlist);
    }

    public string ToString(T FromEnum)
    {
        return FromEnum.ToString();
    }
    public string ToString(IEnumerable<T> FromFlagsList)
    {
        return ToString(ToEnum(FromFlagsList));
    }

    public object ToUnderlyingType(T FromeEnum)
    {
        return Convert.ChangeType(FromeEnum , UnderlyingType);
    }
}
 EnumConverter<ModifierKeys> conv = new EnumConverter<ModifierKeys>();
 //conv.ToEnum
 //conv.ToFlagsList
 //conv.ToString
How to make [Flags] enum and switch case work together?

How to make [Flags] enum and switch case work together?


By : jbm
Date : March 29 2020, 07:55 AM
will be helpful for those in need How to make [Flags] enum and switch case work together? Very desirable to make it looks simple. Similar Questions asked many times, but never directly to [Flags] enum. , This will execute for any bit set
for example
code :
ExecuteOnFlagValue(TST.M1 | TST.M3); //1+2= 3
public void ExecuteOnFlagValue(TST value) {
    if (value & TST.M1 == TST.M1) {
        //Do work if bit 1
    }
    if (value & TST.M2 == TST.M2) {
        //Do work if bit 2
    }
    if (value & TST.M3 == TST.M3) {
        //Do work if bit 3
    }
}
Check for Enum equals with Enum value composed from Enum flags

Check for Enum equals with Enum value composed from Enum flags


By : TomGeronimo
Date : March 29 2020, 07:55 AM
I wish did fix the issue. First of all I am very sorry for the title, but its quite impossible (for me) to come up with a fitting title. , I think you're looking for this:
code :
var test = TknType.Numeric;

if ((test & TknType.Numeric) == TknType.Numeric) 
{
    Console.WriteLine("Test has Numeric flag");
} 
else if ((test & TknType.Number) == TknType.Number) 
{
    Console.WriteLine("Test has Number flag");
}
else if ((test & TknType.Constant) == TknType.Constant) 
{
    Console.WriteLine("Test has Constant flag");
}
Related Posts Related Posts :
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • Drop SQLite tables using list of tables names
  • Can I organize Git submodules in a flat hierarchy?
  • How to make a server reply after receiving a request/data
  • Stored Procedure works in DB but not in C# code
  • MVVM WPF Programmatically add Child Elements
  • NCrunch and PostSharp Logging clash
  • Increasing memory usage in socket client
  • Multiple DropDownList but same action
  • How to get application memory usage as shown in Task Manager?
  • Exposing interfaces instead of concrete classes
  • How to get only postal_code data from google api?
  • Is there a way to get rid of the (by dot42) using community licence?
  • Why must I implement a function for an interface in vb.net which apparently doesn't need to be implemented in C#
  • How to remove HTML tags from the gridview Row
  • Get public post from Facebook's Graph Search API 2.x with Facebook SDK for .NET
  • C# DLL Export to Inno-Setup - Error E0434F4D
  • syntax error insert into database
  • By-pass else block of int.TryParse in Lambda Syntax
  • Retrieve "property getter" from the property name
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org