9

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.

2
  • I'm a bit scared at the thought of why you'd want this, but no I don't think there is... Commented Nov 17, 2010 at 11:59
  • do you need an union equivalent in c#? Commented Nov 17, 2010 at 12:01

6 Answers 6

9

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());
Sign up to request clarification or add additional context in comments.

Comments

3

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

2

There is a boolean property of Type-type "IsPrimitive" hope this helps you.

Comments

1

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

0

There is nothing like that in the BCL.

Why do you need it?

3 Comments

There is DataType enum in the namespace System.ComponentModel.DataAnnotations but it has values like PhoneNumber,EmailAddress etc.
@Daniel Joseph - those are not just primitive types, as you have asked about. And this Enum is there to support ASP.NET MVC and Dynamic Data controls (so they can be annotated for use on other platforms as well).
There is the System.TypeCode enum for primitive types.
0

Why do you need that? The property is already a "filter" to what kind of data it can accept.

Have a look at :

Overloading properties in C#

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.