Is there any enum in c# which holds c# datatypes. So that I can define a property in a class which accepts datatype (int,string) from the user.
-
I'm a bit scared at the thought of why you'd want this, but no I don't think there is...annakata– annakata2010-11-17 11:59:43 +00:00Commented Nov 17, 2010 at 11:59
-
do you need an union equivalent in c#?Bogdan Maxim– Bogdan Maxim2010-11-17 12:01:23 +00:00Commented Nov 17, 2010 at 12:01
6 Answers
There is the TypeCode Enumeration in System. Looks like it covers all of the base types.
You can get the TypeCode for any object using Type.GetTypeCode():
TypeCode typeCode = Type.GetTypeCode(anObject.GetType());
Comments
Do you simply want to associate an enum value with a string? You might want to use the Description attribute.
public enum MyEnum
{
[Description("My first value.")]
FirstValue,
[Description("My second value.")]
SecondValue,
[Description("My third value.")]
ThirdValue
}
private string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
Another possibility for defining a mapping would be to use a Dictionary<int, string>.
Comments
Based on your edit sounds like you need generics but I still question why a property would acceptably be an int or a string. Those are really very different things which can only lead to upcasting.
Comments
There is nothing like that in the BCL.
Why do you need it?
3 Comments
System.TypeCode enum for primitive types.Why do you need that? The property is already a "filter" to what kind of data it can accept.
Have a look at :