Here is a simple implementation of generic method that get value from array in class and cast it to a type.
private T GetReferenceFieldValue<T>(ReferenceRow referenceRow, string fieldName)
{
var referenceField = referenceRow.field.FirstOrDefault(x => x.name == fieldName);
if (referenceField != null)
{
//Dictionary for actions with types
var typeActions = new Dictionary<Type, Func<object>>
{
{ typeof(DateTime), () => { return DateTime.Parse(referenceField.Item.ToString()); } },
{ typeof(int), () => { return int.Parse(referenceField.Item.ToString()); } },
{ typeof(string), () => { return referenceField.Item.ToString(); } },
{ typeof(Guid), () => { return new Guid(referenceField.Item.ToString()); } },
};
var fieldValue = typeActions[typeof(T)]();
return (T)Convert.ChangeType(fieldValue, typeof(T));
}
return default(T);
}
1 Answer 1
referenceRow.field
The field
name does not comply with the C# naming convention for public members that should be PascalCase. It should also probably be Fields
since it's apparently a collection.
typeActions
Consider changing its name to convertTo
which in this context makes the usage more natural:
var fieldValue = convertTo[typeof(T)]();
Func<object>
Consider using a parameter rahter then using closures. That makes the usage even clearer.
If you define it as
Func<object, object>
and the lambdas as
{ typeof(DateTime), x => { return DateTime.Parse(x.ToString()); } },
you can call it with
var fieldValue = convertTo[typeof(T)](referenceField.Item);
if (referenceField != null)
Avoid unnecessary nesting. You can use a postive condition == null
and return
right away if it's nulll
.
return (T)Convert.ChangeType(fieldValue, typeof(T));
This is redundant. The converted value has already the target type. It just needs to be casted and because the ChangeType
boxes the value anyway, you might as well do it yourself like this:
return (T)(object)typeActions[typeof(T)]();