I am busy building an Enum class to validate a file being imported. I created a custom Attribute class that will take in specified criteria. The problem I am facing is a data type conversion must happen with the data type specified in die Attribute. I want to make it as generic as possible.
This is what I have:
ENUM
[Description("Company ID")]
[ColumnValidation(typeof(int), true, -1)]
CompanyID,
[Description("Company Name")]
[ColumnValidation(typeof(string), true, 50)]
CompanyName,
[Description("Company Status")]
[ColumnValidation(typeof(string), true, 50)]
CompanyStatus,
I have extension methods that will get each attribute value, the one I am having problems with is:
public static T ToDataType<T>(this WoWFileStructure val, object valueToConvert)
{
try
{
return (T)Convert.ChangeType(valueToConvert, val.GetDataType());
}
// Catch format exception when unabe to cast value to required datatype and cast object to its default value
catch (FormatException)
{
var instance = Activator.CreateInstance(typeof(T));
return (T)instance;
}
}
This method gets the Type:
public static Type GetDataType(this WoWFileStructure val)
{
return val.GetAttribute<ColumnValidationAttribute>().GetPropertyType();
}
This is how I call it:
var type = enum.CompanyID.GetDataType();
var value = enum.CompanyID.ToDataType<type>("test");
But then I get error saying:
'type' cannot be used like a type
EDIT Attribute Class
[AttributeUsage(AttributeTargets.Field)]
public class ColumnValidationAttribute : Attribute, IExtendedEnumAttribute
{
private Type propertyType;
private bool isRequired;
private int stringLength;
public ColumnValidationAttribute(Type propertyType, bool isRequired, int stringLength)
{
this.propertyType = propertyType;
this.isRequired = isRequired;
this.stringLength = (int)stringLength;
}
public Type GetPropertyType()
{
return propertyType;
}
public bool IsRequired()
{
return isRequired;
}
public int GetStringLength()
{
return stringLength;
}
}