Reputation: 19308
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.
Upvotes: 1
Views: 875
Reputation: 1804
No need to test for HasValue, since Nullable is a struct, you can impose the "new()" constraint:
public void FixedWrite<T>(StreamWriter writer, T value, int length) where T : new()
{
// just test for NULL
string strVal = (value==null) ? string.Empty: value.ToString();
FixedWrite(writer, strVal, length);
}
Now you call it like so (using the "?" notation is the key):
FixedValue<System.DateTime?>(....)
Upvotes: 1
Reputation: 8645
The simple answer is no.
Even tho it is a struct, it's been specifically disallowed in the CLR due to recursion issues that could arise.
Nullable<Nullable<Nullable<etc.>>>()
Upvotes: 0
Reputation: 41378
public void FixedWrite<T>(StreamWriter writer, Nullable<T> value, int length)
Anything wrong with that?
Upvotes: 3
Reputation: 351506
Try something like this:
public void FixedWrite<T>(StreamWriter writer, Nullable<T> value, int length)
where T : struct
{
string strVal;
if (!value.HasValue) strVal = null;
else strVal = value.HasValue.ToString();
FixedWrite(writer, strVal, length);
}
Upvotes: 12