Neil
Neil

Reputation: 3150

Dynamically determine type to cast to (C#)

My function receives a parameter 'value', of type object. I want to assign it to a member of an object, but the cast doesn't happen implicitly, so I need to specify it explicitly. However, I don't want to actually specify the current type of that member in the object, so I could do this:

positiveOrder.OrderID = (int)value;

But, if business requirements change and OrderIDs are generated and stored in a different way, including a type change to Strings for GUIDS for example, I'll have to come back here and change it, which is undesirable cohesion. I've experimented with various permutations of code like

positiveOrder.OrderID = value as thisOrder.OrderID.GetType();

or

positiveOrder.OrderID = (typeof(thisOrder.OrderID)) value;

But nothing seems to be working. Any ideas on programatically specifying the type to convert to? It can be done at compile time or run time, since the Order class doesn't change.

Upvotes: 0

Views: 2753

Answers (2)

Codesleuth
Codesleuth

Reputation: 10541

If positiveOrder.OrderID will always be an integer (even if represented in a string), don't change the member to be anything but an integer. Instead, expose some method that can deal with different source types.

For example:

public void SetOrderID(object value)
{
    this.OrderID = Convert.ToInt32(value);
}

See Convert.ToInt32().

Upvotes: 2

Thom Smith
Thom Smith

Reputation: 14086

Something like:

using System.Reflection;

receiver.GetType().GetProperty(propName).SetValue(receiver, value, null);

Upvotes: 0

Related Questions