Stan
Stan

Reputation: 26501

Universal way to convert object to other data types?

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?

What I have now

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);
}

What I would like to have (pseudo)

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

Answers (2)

SLaks
SLaks

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

nirmus
nirmus

Reputation: 5093

public T GetValue<T>(string key, T type)
{
    return Convert.ChangeType(object.FirstOrDefault(x => x.Key == key).Value, typeof(T));
}

Upvotes: 1

Related Questions