Reputation: 1546
I have a class a binary masque:
public class Masque
{
public bool MasquerAdresse { get; set; }
public bool MasquerCpVille { get; set; }
public bool MasquerTelephone { get; set; }
public bool MasquerFax { get; set; }
public bool MasquerEmail { get; set; }
public bool MasquerNom { get; set; }
}
and in the database I have a binary masque field: when i have the value 1=> MasquerAdresse is true, 2 =>MasquerCpVille is true, 4=> MasquerTelephone is true 3=> MasquerAdresse and MasquerCpVille are true etc..., which is the best methode to decode this binary masque in c#
Upvotes: 1
Views: 75
Reputation: 2398
As others already pointed out in C# we usually use Flag Enums and Enum.HasFlag()
to do this. As @Groo added in his comment this is also more memory efficient since every bool takes up an entire byte. Using enums it would look like this:
[Flags]
public enum Masque
{
MasquerAdresse = 1,
MasquerCpVille = 2,
MasquerTelephone = 4,
MasquerFax = 8,
MasquerEmail = 16
MasquerNom = 32
}
var masque = Masque.MasquerAdresse | Masque.MasquerTelephone;
var fromInt = (Masque) 5;
var trueResult = masque.HasFlag(Masque.MasquerTelephone);
If you are however determined to use a class it would look like this:
public class Masque
{
public bool MasquerAdresse { get; set; }
public bool MasquerCpVille { get; set; }
public bool MasquerTelephone { get; set; }
public bool MasquerFax { get; set; }
public bool MasquerEmail { get; set; }
public bool MasquerNom { get; set; }
public static Masque FromBits(int bits)
{
return new Masque
{
MasquerAdresse = (bits & 1) > 0,
MasquerCpVille = (bits & 2) > 0,
...
};
}
}
Using the binary &
it will apply the bit mask which either returns the value or 0. You can either compare the result with the mask (bits & 2) == 2
or simply check for > 0
.
Upvotes: 4