Question

Is it possible to change the data type of a field/property in .net through reflection or something?

I am looking for this feature, as there is problem in Strongly Typed Datasets. Strongly Typed Datasets don't give You the flexibility of changing data types of nullable types. See a related link here. So, if there is a possibility to change the data type at run time, this problem can be eliminated. Also, to add; as per this MSDN Link; Microsoft team is not very keen to provide this support.

Was it helpful?

Solution

First, this is not a bug; it's due to the difference between dbnull ie unknown value and null ie a reference pointing nowhere. It's compounded by the fact that Microsoft themselves seem to be poor at explaining it, judging by some of the opaque and unhelpful responses on Connect and elsewhere.

There are a number of solutions to this issue, depending on what you are trying to achieve. If you are using databinding, then the binding mechanism mostly handles this transparently for you; if you are hitting the dataset directly in code the designer will have built Isxxxnull / setxxxnull methods for you to check the value before you use it. Finally you can change the datatype to system.object, or you can overtype the NullValue in the designer to enter another value if you wish, as long as that value is valid for the datatype - eg 0 or -1 for an int.

OTHER TIPS

Not that I'm aware of. Type information and binding is determined at compile-type, so there's not a way to change it at run time.

One pattern to use to change typing is the adapter pattern. This could just pass through all other fields and then "convert" the field in question to a new type. Of course, this happens at compile-time as well.

If you expand a little more on what you're trying to do there may be a better option.

Datasets are rather dated and stem from .net v1.0. Microsoft is never going make changes or additions to them. In general a better approach would be strongly typed POCOs. You can even create multiple, strongly typed properties that all use the same backing storage (of type object). You would need to test for the correct type before accessing the corresponding property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top