Reputation: 26501
I have multiple lines where I expicitly say that I want to convert something to string
or bool
or date
etc..
Is it possible to somehow encapsulate it within method where I pass object that I want to convert and also pass what I want to get in return?
foreach (var item in archive.Items)
{
var newItem = new Item();
newItem.Notes = Convert.ToString(item.FirstOrDefault(x => x.Key == "notes").Value);
newItem.IsPublic = Convert.ToBoolean(item.FirstOrDefault(x => x.Key == "ispublic").Value);
}
foreach (var item in archive.Items)
{
var newItem = new Item();
newItem.Notes = GetValue("notes", string)
newItem.IsPublic = GetValue("ispublic", bool)
}
// ...
public T GetValue(string key, T type)
{
return object.FirstOrDefault(x => x.Key == key).Value; // Convert this object to T and return?
}
Is something like this even possible?
Upvotes: 1
Views: 603
Reputation: 887275
You'll want to write a generic wrapper around Convert.ChangeType()
:
public T GetValue<T>(string key) {
return (T)Convert.ChangeType(..., typeof(T));
}
Upvotes: 5
Reputation: 5093
public T GetValue<T>(string key, T type)
{
return Convert.ChangeType(object.FirstOrDefault(x => x.Key == key).Value, typeof(T));
}
Upvotes: 1