Quote:
quote:Originally posted by john316
NewMethodName(rs["Surname"], cust.Surname);
NewMethodName(rs["BankAmount"], cust.Amount);
|
Unfortunately you can't do this the way you want. Passing a simple type property to a method simply passes the value. You can't use ref or out parameters either because of the way properties work. A property is really two methods (the Get and Set) so you can't technically pass them as references even if the type exposed would normally be a reference type (non-primitive).
Doug's suggestion of a class that does this with reflection, to me, seems like major overkill. Reflection is slower and excessive for doing something that can be achieved in a few small methods.
Your problem is a typical problem people deal with when creating the object-to-relational plumbing of a data driven app. I usually do this kind of thing with a few helper methods in a base data access layer class that I extend for each of the specific data access classes.
The methods are usually something like this:
Code:
protected string GetString(object value){
//Test for DBNull here
//return appropriate value (value.ToString(), string.Empty, etc.)
}
Often, I'll overload those methods to support default values:
Code:
protected string GetString(object value, string defaultValue){
//Test for DBNull here, return default if null
//return value.ToString()
}
protected string GetString(object value){
return GetString(value, string.Empty);
}
Create these helper methods for all data types you need. You may find there aren't as many as you'd think. For numeric types you can use generics for a single set of methods that handles all those types, for example:
Code:
protected T GetNumeric<T>(object value, T defaultValue){
if(value is DBNull) return defaultValue;
return (T)value; //cast value to generic type
}
protected T GetNumeric<T>(object value){
return GetNumeric<T>(value, 0);
}
Although I haven't tried it, you could probably get away with a single generic method for most types, although this limits the ability to create a single parameter "default return" method:
Code:
protected T GetDbValue<T>(object value, T defaultValue){
if(value is DBNull) return defaultValue;
return (T)value; //cast value to generic type
}
//protected T GetDbValue<T>(object value){
// return GetDbValue<T>(value, ???); //Can't really do this
//}
The dissadvantage of the generic approach is that you calls to the methods are more verbose. You may be better to create some methods for the discreet types you know you need to deal with (strings, numerics, etc.) but also have a generic method for those other cases. This will provide the flexibility and simplicity in the helper methods while keeping your consuming code cleaner.
-Peter