Enumeration Objects (Strings) in Entity Framework - c#

I am building a model with Entity Framework and purchased responsive CSS.
The built in fixed icons comes with CSS. Like as follows (Name and Icon Class Value)
I need a way to keep the names of icons as fixed enums to access it from the VS intellisense. Currently we can't store as a entity table in entity framework (as it require relationship with tables difficult to maintain) and enum doesn't allows string type.
Code that did not work:
public sealed class IconType
{
public static readonly IconType Rupee_Icon = new IconType("rupee-icons");
public static readonly IconType Doller_Icon = new IconType("doller-icon");
private IconType(int EnumID,string EnumObjectValue)
{
IconValue = EnumObjectValue;
}
public string IconValue { get; private set; }
}
More code that did not work (CSS class names contains whitespaces like ui bell icon):
public enum Icon
{
NotSet=0,
Idea Icon=1,
Bell Icon =2
}
Is there any other ways to use names / objects as enums or constants in EF for easy intellisense in Visual Studio?

You could:
Omit the white spaces in the enums:
public enum Icon
{
NotSet = 0,
IdeaIcon = 1,
BellIcon = 2
}
Add a description or name (Or even some custom attribute) attributes to the enums:
public enum Icon
{
NotSet = 0,
[Description("ui idea icon")]
IdeaIcon = 1,
[Description("ui bell icon")]
BellIcon = 2
}
When needed get the description name. Example method to get the description attribute value:
public static string GetDescription<T>(this T enumerationValue)
where T : struct, IConvertible
{
var type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
// Tries to find a DescriptionAttribute for a potential friendly name for the enum
var memberInfo = type.GetMember(enumerationValue.ToString(CultureInfo.InvariantCulture));
if (memberInfo.Length > 0)
{
var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
// Pull out the description value
return ((DescriptionAttribute)attributes[0]).Description;
}
}
// If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString(CultureInfo.InvariantCulture);
}

Did you consider using string constants?
public static class IconType
{
public const string RUPEE_ICON = "rupee-icon";
public const string DOLLER_ICON = "doller-icon";
// ...
}

Store the icon's as plain old objects. Why make use of entity framework at all?
public static class Icons
{
public enum Type
{
IdeaIcon = 1,
BellIcon =2
}
public static Icon Get(Type type)
{
return IconCollection.Single(icon => icon.Type == type);
}
static IEnumerable<Icon> IconCollection
{
get
{
return new List<Icon>
{
new Icon(Type.IdeaIcon, "Idea Icon", "icon idea-icon"),
new Icon(Type.BellIcon, "Bell Icon", "icon bell-icon"),
};
}
}
public class Icon
{
public Icon(Type type, string description, string cssClass)
{
Type = type;
Description = description;
CssClass = cssClass;
}
public Type Type { get; private set; }
public string Description { get; private set; }
public string CssClass { get; private set; }
}
}
Use in code:
public class Class1
{
public void Method1()
{
var ideaIcon = Icons.Get(Icons.Type.IdeaIcon);
var x = ideaIcon.CssClass;
var y = ideaIcon.Description;
var bellIcon = Icons.Get(Icons.Type.BellIcon);
// etc...
}
}
Razor view:
#Icons.Get(Icons.Type.BellIcon).CssClass
If you needed to enumerate over the icon collection you could easily add another static accessor to the Icons class.

Related

Best practice for an enum in a class changing a return of a function

So for instance you have an object with a type for sounds, and based on the enum a particular function will do play a different sound depending on the type
public enum ObjectType{
Type1,
Type2,
Type3
}
public class Object{
public ObjectType type;
public Sound sound;
private void DoThing(){
if(type == ObjectType.Type1){
sound = Load("sounds/sound1");
}
if(type == ObjectType.Type2){
sound = Load("sounds/sound2");
}
//etc...
}
}
I guess my question is, when this enum will grow larger in size into the tens or hundreds, what's the best practice to organize and test against the enum to return another value?
Should I be using a switch case rather than a bunch of if tests? Mostly just regarding organization, these functions aren't really resource heavy and won't be using a lot of computation, so performance isn't really my concern, mostly readability.
If you have hundreds of values an enum might not be the best representation, but in general if you have a lot of items you need to fetch based on some value you would build a lookup table.
You can build that table once, then it's just a single line of code to fetch the correct item based on the enum value in question.
public class MyObject
{
private ObjectType type;
private Sound sound;
private static Dictionary<ObjectType, Sound> soundLookup = new Dictionary<ObjectType, Sound>()
{
{ ObjectType.Type1, Load("sounds/sound1") },
{ ObjectType.Type2, Load("sounds/sound2") },
{ ObjectType.Type3, Load("sounds/sound3") },
// etc.
{ ObjectType.Type99, Load("sounds/sound99") },
};
public MyObject(ObjectType objectType)
{
this.type = objectType;
this.sound = soundLookup[objectType];
}
private void DoThing()
{
var sound = this.sound;
// Do something with sound.
}
private static Sound Load(string soundPath)
{
return new Sound();
}
}
If you're able to have a naming convention with your sound files and ObjectTypes, then this becomes a pattern matching issue. For instance, if you define your enums like:
public enum ObjectType
{
Type1 = 1,
Type2 = 2,
Type3 = 3
}
Then you can replace your method with:
sound = Load($"sounds/sound{(int)type}");
Which (for example, type is Type1) for the above line would find "sound1"
If you can't setup the values with the enum, but still have numbers in the name itself, you're able to retrieve those numbers by:
// Call to replace to get the number, and not the "Type" prefix
string number = Enum.GetName(typeof(ObjectType), type).Replace("Type", "");
With the following usage:
sound = Load($"sounds/sound{number}");
Edit: Full Example
public enum ObjectType{
Type1,
Type2,
Type3
}
public class Object{
public ObjectType type;
public Sound sound;
private void DoThing(){
string number = Enum.GetName(typeof(ObjectType), type).Replace("Type", "");
sound = Load($"sounds/sound{number}");
}
}
To keep additional metadata inline with the enum definition, you could build a dictionary based on custom attributes.
public SoundAttribute : Attribute {
public string File { get; set; }
}
public enum ObjectType{
[Sound(File = "sound1")]
Type1,
[Sound(File = "sound2")]
Type2,
[Sound(File = "sound3")]
Type3
}
public static Dictionary<ObjectType, SoundAttribute> Sounds =
typeof(ObjectType)
.GetFields(BindingFlags.Static | BindingFlags.Public)
.ToDictionary(
f => (ObjectType)f.GetValue(null),
f => f.GetCustomAttribute<SoundAttribute>()
);
Here's a closer implementation of what I was trying to accomplish.
I think it's at least better than the switch method I was trying to do, but I'm still trying to figure out that enum.
The object type will be manually set no matter what before the instantiation by a dropdown which will be populated each time a new object type is manually created, so I assume an enum is still the best use for this, but I could be wrong.
public class MyObject
{
public ObjectType type;
public string soundPath;
public string otherSoundPath;
public Sound sound;
public Sound otherSound;
private void Start()
{
type = Self.type;
soundPath = GetSoundPath(type, false);
otherSoundPath = GetSoundPath(type, true);
sound = Load($"\\sounds\\{soundPath}");
otherSound = Load($"\\sounds\\{otherSoundPath}");
}
public string GetSoundPath(ObjectType type, bool isOtherClip)
{
string soundPath = string.Empty;
if (!isOtherClip)
{
if (!sounds.TryGetValue(type, out soundPath))
{
soundPath = "defaultClip";
}
}
else
{
if (!otherSounds.TryGetValue(type, out soundPath))
{
soundPath = "defaultOtherClip";
}
}
return soundPath;
}
private Dictionary<ObjectType, string> sounds = new Dictionary<ObjectType, string>
{
{ ObjectType.A, "a" },
{ ObjectType.B, "b" },
{ ObjectType.C, "c" },
};
private Dictionary<ObjectType, string> otherSounds = new Dictionary<ObjectType, string>
{
{ ObjectType.A, "a" },
{ ObjectType.B, "b" },
{ ObjectType.C, "c" },
};
}
public enum ObjectType
{
A,
B,
C
}

Editing an enum in a class (member cannot be accessed with an instance reference)

I'm trying to edit an enum value in a class instance based on whether that instance appears in a dictionary of type <string, myClass>. What seems logical to me is to do the code snippets below:
if (pumpDict.ContainsKey(ID))
{
foreach(KeyValuePair<string, PumpItem> kvp in pumpDict)
{
if(kvp.Key == ID)
{
kvp.Value.state = kvp.Value.state.Available; //error here
kvp.Value.fuelPumped = fuelPumped;
kvp.Value.fuelCost = fuelCost;
break;
}
}
}
else
{
PumpItem pump = new PumpItem();
pumpDict.Add(ID, pump);
}
And my PumpItems class is such:
namespace PoSClientWPF
{
public enum pumpState
{
Available,
customerWaiting,
Pumping,
customerPaying
};
public enum fuelSelection
{
Petrol,
Diesel,
LPG,
Hydrogen,
None
};
class PumpItem
{
public double fuelPumped;
public double fuelCost;
public fuelSelection selection;
public pumpState state;
public PumpItem()//intialize constructor
{
this.fuelPumped = 0;
this.fuelCost = 0;
this.selection = fuelSelection.None;
this.state = pumpState.Available;
}
}
}
I was led to believe that to have an enum value in a constructor, they have to be set up as above, with a new instance of those enums declared in the class body.
It seems to me, that what I'm trying to do is logical but I am getting an error on the right hand side of the assignation which states:
"member PoSClientWPF.pumpState.Available cannot be accessed with an instance reference; qualify is with a type name instead"
I've searched for this error among several forums but only seem to find errors involving calling static variables incorrectly. Can anyone point me in the direction of a solution?
Thanks in advance.
You are incorrectly accessing the Enum member:
// this is incorrect
kvp.Value.state = kvp.Value.state.Available; //error here
// this is the correct way
kvp.Value.state = PoSClientWPF.pumpState.Available;
You know you have a dictionary?
PumpItem pumpItem = pumpDict[ID];
pumpItem.state = PoSClientWPF.pumpState.Available;
or
PumpItem pumpItem;
if (pumpDict.TryGetValue(ID, out pumpItem))
{
pumpItem.state = PoSClientWPF.pumpState.Available;
}
else
{
pumpItem = new PumpItem();
pumpDict.Add(ID, pumpItem);
}
Could just add ID to PumpItem and use a List
PumpItem pumpItem = pumpList.FirstOrDefualt(x => x.ID == ID)
if (pumpItem == null)
pumpList.Add(new PumpItem(ID));
else
pumpItem.state = PoSClientWPF.pumpState.Available;
class PumpItem
{
public double fuelPumped = 0;
public double fuelCost = 0;
public fuelSelection selection = fuelSelection.None;
public pumpState state = pumpState.Available;
public Int32? ID = null;
public PumpItem()//intialize constructor
{ }
public PumpItem(Int32? ID)
{
this.ID = ID;
}
}

How do I retrieve data from a list<> containing class objects

I want to retrieve data from a list I created that contains class objects via a foreach but I'm not able to.
Can somebody please tell me what's missing in my code?
I have a class Recipes.cs that contains the following code:
public class Recipe
{
string _oveskrift;
int _recipe_id;
string _opskrift;
int _kcal;
public Recipe(string overskrift, int recipe_id, string opskrift,int kcal)
{
_oveskrift = overskrift;
_recipe_id = recipe_id;
_opskrift = opskrift;
_kcal = kcal;
}
}
public class Recipes
{
public List<Recipe> CreateRecipeList()
{
Recipe opskrift1 = new Recipe("Cornflakes med Chili",1,"4 kg cornflakes bages", 420);
Recipe opskrift2 = new Recipe("Oksemørbrad",2,"Oksemørbrad steges i baconfedt", 680);
Recipe opskrift3 = new Recipe("Tun i vand",3,"Dåsen åbnes og tunen spises", 120);
List<Recipe> Recipelist = new List<Recipe>();
Recipelist.Add(opskrift1);
Recipelist.Add(opskrift2);
Recipelist.Add(opskrift3);
return Recipelist;
}
}
I call CreateRecipeList() from another class calculator.cs and the code looks like this:
private int FindRecipes()
{
List<Recipe> Rlist = new List<Recipe>();
// CREATE THE CLASS AND ADD DATA TO THE LIST
Recipes r = new Recipes();
Rlist = r.CreateRecipeList();
int test = 0; // used only for test purposes
foreach(var rec in Rlist)
{
rec.????
test++;
}
return test;
}
I would presume that I should be able to dot my way into rec."the class object name"."the value"
But nothing happens!.
All I get is the option to rec.Equals, rec.GetHashcod ect. which is clearly wrong.
For the record I have also tried:
foreach(Recipe rec in Rlist)
{
rec.????
test++;
}
But that doesn't work either.
The Int test are only there for test purposes.. and it return 3.. so the list does contain the correct information.
Please show us the code for the Recipe class. Besides that, you're most of the way there...
foreach(Recipe rec in Rlist)
{
string str = rec.<PropertyName>;
}
You need to set the proper access modifiers for the members in your Recipe class.
public : Access is not restricted.
protected : Access is limited to the containing class or types derived from the containing class.
Internal : Access is limited to the current assembly.
protected internal: Access is limited to the current assembly or types derived from the containing class.
private : Access is limited to the containing type.
By default, the members of your Recipe class will have the private access modifier.
string _oveskrift;
int _recipe_id;
string _opskrift;
int _kcal;
is:
private string _oveskrift;
private int _recipe_id;
private string _opskrift;
private int _kcal;
Maybe you want to modify your member access as follows, in order to set the values of the members only inside the class code. Any attempt to set their values outside the Recipe class will fail, as the set is private. The get remains public, which makes the value available for reading.
public class Recipe
{
string _oveskrift;
int _recipe_id;
string _opskrift;
int _kcal;
public string Oveskrift
{
get
{
return _oveskrift;
}
private set
{
_oveskrift=value;
}
}
public int RecipeId
{
get
{
return _recipe_id;
}
private set
{
_recipe_id = value;
}
}
public string Opskrift
{
get
{
return _opskrift;
}
private set
{
_opskrift = value;
}
}
public int Kcal
{
get
{
return _kcal;
}
private set
{
_kcal = value;
}
}
public Recipe(string overskrift, int recipe_id, string opskrift, int kcal)
{
_oveskrift = overskrift;
_recipe_id = recipe_id;
_opskrift = opskrift;
_kcal = kcal;
}
}
Also, please read as soon as possible the following MSDN article: Capitalization Conventions. And also, this one: C# Coding Conventions (C# Programming Guide).

Reflection - object comparison & default values

I'm trying to compare two complex objects in C#, and produce a Dictionary containing the differences between the two.
If I have a class like so:
public class Product
{
public int Id {get; set;}
public bool IsWhatever {get; set;}
public string Something {get; set;}
public int SomeOtherId {get; set;}
}
And one instance, thus:
var p = new Product
{
Id = 1,
IsWhatever = false,
Something = "Pony",
SomeOtherId = 5
};
and another:
var newP = new Product
{
Id = 1,
IsWhatever = true
};
To get the differences between these, i'm doing stuff that includes this:
var oldProps = p.GetType().GetProperties();
var newProps = newP.GetType().GetProperties();
// snip
foreach(var newInfo in newProps)
{
var oldVal = oldInfo.GetValue(oldVersion, null);
var newVal = newInfo.GetValue(newVersion,null);
}
// snip - some ifs & thens & other stuff
and it's this line that's of interest
var newVal = newInfo.GetValue(newVersion,null);
Using the example objects above, this line would give me a default value of 0 for SomeOtherId (same story for bools & DateTimes & whathaveyou).
What i'm looking for is a way to have newProps include only the properties that are explicitly specified in the object, so in the above example, Id and IsWhatever. I've played about with BindingFlags to no avail.
Is this possible? Is there a cleaner/better way to do it, or a tool that's out there to save me the trouble?
Thanks.
There is no flag to tell if you a property was explicitly set. What you could do is declare your properties as nullable types and compare value to null.
If i understand you correctly, this is what microsoft did with the xml wrapping classes, generated with the xsd utility, where you had a XIsSpecified, or something like that, for each property X.
So this is what You can do as well - instead of public int ID{get;set;}, add a private member _id , or whatever you choose to call it, and a boolean property IDSpecified which will be set to true whenever Id's setter is called
I ended up fixing the issue without using reflection (or, not using it in this way at least).
It goes, more or less, like this:
public class Comparable
{
private IDictionary<string, object> _cache;
public Comparable()
{
_cache = new Dictionary<string, object>();
}
public IDictionary<string, object> Cache { get { return _cache; } }
protected void Add(string name, object val)
{
_cache.Add(name, val);
}
}
And the product implementation goes to this:
public class Product : Comparable
{
private int _id;
private bool _isWhatever;
private string _something;
private int _someOtherId;
public int Id {get { return _id; } set{ _id = value; Add("Id", value); } }
public bool IsWhatever { get { return _isWhatever; } set{ _isWhatever = value; Add("IsWhatever ", value); } }
public string Something {get { return _something; } set{ _something = value; Add("Something ", value); } }
public int SomeOtherId {get { return _someOtherId; } set{ _someOtherId = value; Add("SomeOtherId", value); } }
}
And the comparison is then pretty straightforward
var dic = new Dictionary<string, object>();
foreach(var obj in version1.Cache)
{
foreach(var newObj in version2.Cache)
{
//snip -- do stuff to check equality
dic.Add(....);
}
}
Doesn't hugely dirty the model, and works nicely.

Enumerate with return type other than string?

Since enumeration uses integers, what other structure can I use to give me enum-like access to the value linked to the name:
[I know this is wrong, looking for alternative]
private enum Project
{
Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1"),
Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2"),
Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1"),
Sales = new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435"),
Replacement = new Guid("11E5CBA2-EDDE-4ECA-BDFD-63BDBA725C8C"),
Modem = new Guid("6F686C73-504B-111-9A0B-850C26FDB25F"),
Audit = new Guid("30558C7-66D9-4189-9BD9-2B87D11190"),
Queries = new Guid("9985242-516A-4151-B7DD-851112F562")
}
EDIT 2014-07-20
This is a newer answer to this question. Using the Attribute class with a helper method, define the extra attributes needed on your enum.
public enum MultiValueEnum
{
[FooAttribute("alpha", 20d, true)]
First,
[FooAttribute("beta", 40.91d, false)]
Second,
[FooAttribute("gamma", 1.2d, false)]
Third,
}
public class FooAttribute : Attribute
{
internal FooAttribute(string name, double percentage, bool isGood)
{
this.Name = name;
this.Percentage = (decimal)percentage;
this.IsGood = isGood;
}
public string Name { get; private set; }
public decimal Percentage { get; private set; }
public bool IsGood { get; private set; }
}
public static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}
Which makes it this easy:
MultiValueEnum enumVar = MultiValueEnum.First;
var enumStringValue = enumVar.GetAttribute<FooAttribute>().Name;
var enumValueDecimal = enumVar.GetAttribute<FooAttribute>().Percentage;
var enumBool = enumVar.GetAttribute<FooAttribute>().IsGood;
Otherwise you could create a custom Attribute for your enum, which can hold the Guid.
Something alongside these lines:
class EnumGuid : Attribute
{
public Guid Guid;
public EnumGuid(string guid)
{
Guid = new Guid(guid);
}
}
And you'd then use it like so:
enum Project
{
[EnumGuid("2ED3164-BB48-499B-86C4-A2B1114BF1")]
Cleanup = 1,
[EnumGuid("39D31D4-28EC-4832-827B-A11129EB2")]
Maintenance = 2
// and so forth, notice the integer value isn't supposed to be used,
// it's merely there because not assigning any value is a performance overhead.
}
And finally you could (I always do this) create an extension for easily getting the guid:
static Guid GetEnumGuid(this Enum e)
{
Type type = e.GetType();
MemberInfo[] memInfo = type.GetMember(e.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumGuid),false);
if (attrs != null && attrs.Length > 0)
return ((EnumGuid)attrs[0]).Guid;
}
throw new ArgumentException("Enum " + e.ToString() + " has no EnumGuid defined!");
}
So in the end all you have to with your enums is:
Guid guid = Project.Cleanup.GetEnumGuid();
I use this approach to attach descriptions to enums, typically longer strings containing spaces, which thus cannot be used as names.
I've seen this method (struct) used by SubSonic to store Column and Table names.
internal struct Project
{
public static Guid Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1");
public static Guid Maintenance = new Guid("39D31D4-28EC-4832-827B-A129EB2");
public static Guid Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1");
public static Guid Sales = new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435");
public static Guid Replacement = new Guid("11E5CBA2-EDDE-4ECA-BD63-B725C8C");
public static Guid Modem = new Guid("6F686C73-504B-111-9A0B-850C26FDB25F");
public static Guid Audit = new Guid("30558C7-66D9-4189-9BD9-2B87D11190");
public static Guid Queries = new Guid("9985242-516A-4151-B7DD-851112F562");
}
EDIT:- Thanks for commenting on deficiencies in code. In first place it will compile if the Guid strings are not invalid. As for not create instances to access variables yes they need to be public static
I would probably go the dictionary route on this one. Have a lookup table basically:
public class GuidMapper
{
private Dictionary<GuidTypes, Guid> mGuidMap = new Dictionary<GuidTypes, Guid>();
public enum GuidTypes: int
{
Cleanup,
Maintenance,
Upgrade,
Sales,
Replacement,
Modem,
Audit,
Queries
}
public GuidMapper()
{
mGuidMap.Add(GuidTypes.Cleanup, new Guid("2ED31640-BB48-499B-86C4-A2B1114BF100"));
mGuidMap.Add(GuidTypes.Maintenance, new Guid("39D31D40-28EC-4832-827B-A11129EB2000"));
mGuidMap.Add(GuidTypes.Upgrade, new Guid("892F8650-E38D-46D7-809A-49510111C100"));
mGuidMap.Add(GuidTypes.Sales, new Guid("A5690E70-1111-4AFB-B44D-1DF3AD66D435"));
mGuidMap.Add(GuidTypes.Replacement, new Guid("11E5CBA2-EDDE-4ECA-BDFD-63BDBA725C8C"));
mGuidMap.Add(GuidTypes.Modem, new Guid("6F686C73-504B-1110-9A0B-850C26FDB25F"));
mGuidMap.Add(GuidTypes.Audit, new Guid("30558C70-66D9-4189-9BD9-2B87D1119000"));
mGuidMap.Add(GuidTypes.Queries, new Guid("99852420-516A-4151-B7DD-851112F56200"));
}
public Guid GetGuid(GuidTypes guidType)
{
if (mGuidMap.ContainsKey(guidType))
{
return mGuidMap[guidType];
}
return Guid.Empty;
}
}
If you need proper enum-like semantics and type-safety then you can use a pattern like this.
(You could flesh it out further if you require extras like conversion operators, GetUnderlyingType, ToString etc. If you wanted to re-use the pattern for multiple enum-like classes with different underlying types then you could move any common code into a generic, abstract base class.)
Project x = Project.Cleanup;
Project y = Project.Cleanup;
Project z = Project.Maintenance;
Console.WriteLine(x == y); // True
Console.WriteLine(x == z); // False
Console.WriteLine(x.Value); // 47801daa-7437-4bfe-a240-9f7c583018a4
// this line will cause a compiler error
Console.WriteLine(x == new Guid("47801daa-7437-4bfe-a240-9f7c583018a4"));
// ...
public class Project
{
private Project(Guid v) { Value = v; }
public Guid Value { get; private set; }
public static readonly Project Cleanup =
new Project(new Guid("47801daa-7437-4bfe-a240-9f7c583018a4"));
public static readonly Project Maintenence =
new Project(new Guid("2548a7f3-7bf4-4533-a6c1-dcbcfcdc26a5"));
public static readonly Project Upgrade =
new Project(new Guid("ed3c3e73-8e6a-4c09-84ae-7f0876d194aa"));
}
When confronted with this kind of problem I used structs with consts as public members:
public struct FileExtensions
{
public const string ProcessingExtension = ".lck";
public const string ProcessedExtension = ".xml";
public const string FailedExtension = ".failed";
public const string CsvExtension = ".csv";
}
You could create a static class that just contains constant values.
For example:
internal static class Project
{
public static readonly Guid Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1");
public static readonly Guid Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2");
public static readonly Guid Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1");
}
This way the class acts simply as a container and object cannot be created from it.
In VB this would be a Module:
Friend Module Project
Public Shared ReadOnly Cleanup As Guid = New Guid("2ED3164-BB48-499B-86C4-A2B1114BF1")
Public Shared ReadOnly Maintenance As Guid = New Guid("39D31D4-28EC-4832-827B-A11129EB2")
Public Shared ReadOnly Upgrade As Guid = New Guid("892F865-E38D-46D7-809A-49510111C1")
End Module
The enum type can only support the integral types (except char) as its value. You could however use something like a Dictionary to do lookups of a a name to a value.
Dictionary<Guid> lookup = new Dictionary<Guid>();
lookup["Cleanup"] = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1");
lookup["Maintenance"] = new Guid("39D31D4-28EC-4832-827B-A11129EB2");
lookup["Upgrade"] = new Guid("892F865-E38D-46D7-809A-49510111C1");
// etc...
Another alternative is to have a series of readonly values in a static class.
public static class Guids
{
public static readonly Guid Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1");
public static readonly Guid Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2");
public static readonly Guid Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1");
}

Categories