V
V
Vlad2021-08-09 11:36:12
.NET
Vlad, 2021-08-09 11:36:12

What is the best way to optimize the following code?

Greetings! I've been blessed with some code that I want to change to a more readable one.
For example, I simplified the class as much as possible. In the current implementation of the program, I have two Enums, one defines the data type - this is the type, the other - the number of bits in the mask with flags.

public class MyClass
{
    public MyTypes type {get; set;}
    public BitArray flags {get; set;}

    public MyClass(MyTypes type)
    {
        this.type = type;
        this.bitarray = new BitArray(MyClass.ReadFlagsLength())
    }

    public static int ReadFlagsLength()
    {
        int bitmapLength = Convert.ToInt32(Enum.Parse(
                typeof(HeaderBitmapsLength),
                this.Type.ToString()
        ));
        return bitmapLength;
    }

    public enum MyTypes : UInt32 
    {
        Type1 = 0x00,
        Type2 = 0x01,
        Type3 = 0x10
    }
    
    public enum MyTypesBitArrayLength : UInt32 
    {
        Type1 = 0x04,
        Type2 = 0x10,
        Type3 = 0x04
    }
}


It works, but I want to make the code simpler. I want to get rid of these conversions c Enum. Only a static constructor comes to mind in which the Type -> BitArrayLength dictionary will be filled, from which I can get the length of the bit array without any transformations. Can this be done even easier?
Option B is a classic switch-case
public static int GetFlagsLength(MyTypes type)
        {
            switch (type)
            {
                case MyTypes.Type1  | MyTypes.Type3 : 
                    return 0x04;

                case MyTypes.Type1 :
                    return 0x10;

                case 
                default:
                    return -1;

            }
        }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question