1
\$\begingroup\$

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);
 }
asked Nov 8, 2016 at 8:22
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$
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)]();
answered Nov 8, 2016 at 8:42
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.