I'm working on a method that will accept a StreamWriter, either a string or a nullable value, and a length, and write the value to the StreamWriter, padded to the length. If the value is null, I want to write spaces. I want to do something like the following oversimplified example, which is just for demonstration purposes.
public void FixedWrite(StreamWriter writer, string value,
int length) {
if (value == null) value = "";
value = value.PadRight(length);
writer.Write(value);
}
public void FixedWrite<T>(StreamWriter writer, T value,
int length) where T : Nullable /* won't work of course */ {
string strVal;
if (!value.HasValue) strVal = null;
else strVal = value.Value.ToString();
FixedWrite(writer, strVal, length);
}
I could have overloads for all the different underlying types (they're all dates, ints, bools and decimals), but I wanted to see if I could get the generic version working. Is there some way of getting T to always be a Nullable<> type, and to access the Nullable<> properties (HasValue and Value)? Or should I just stick with the underlying-type-specific overloads?
This question poses a similar problem, but in my case the values are already nullables and I just want to write out the value if it has one and spaces if it doesn't.