Suppose I have the following class:
public class MyClass
{
public decimal myDecimal;
public string myString;
}
I want to use the DataRowExtensions method Field<>
Currently, I am using the class like so:
MyClass myClass = new MyClass();
myClass.myDecimal = row.Field<decimal>("MyDecimalColumnName");
myClass.myString = row.Field<string>("MyStringColumnName");
However, if I ever decide to change the type of myDecimal to something other than decimal, I want the call to row.Field to reflect the correct data.
I want something similar to the following syntax:
myClass.myDecimal = row.Field<typeof(myClass.myDecimal)>("MyDecimalColumnName");
This doesn’t compile, and I have no idea how to use typeof or GetType() to just return decimal, whatever that would be called.
Is there a way to do this, or something similar? I figured this could accomplished at compile time as the types are already known, and since generics are compile time constructs.
Thanks!
First, note that public fields are usually a very bad idea; but if we assume this was a private backing field, there are 2 interesting options here;
The first is to exploit generic type inference; this doesn’t work for the return type, but does for the parameters, so you could have:
where that is:
Another trick would be to use implicit operators, i.e. have
GetField(string)return a dummy object that has implicit conversion operators to a few types such asint,decimal, etc, and do the work / conversion in the operator. A bit hacky, but would work – syntax would be:with:
and with
SomeDummyTypehaving an implicit static conversion operator or several.However! IMO the best option here is to use a tool such as an ORM or micro-ORM to load the values for you, and don’t use
DataRowat all.Another simple option is just to go old-school:
I mean – is the
.Field<T>really helping you all that much? Do you genuinely refactor your classes often enough that this is worth worrying about it?