Reputation: 26409
In this generic "class":
public class Param<ValueType>{
public ValueType value;
}
When ValueType
is string
I want value
to be non-null for all newly created instances of class without explicitly passing default value through constructor. In my scenario ValueType
can only be int
, float
, bool
, string
or struct
(that doesn't need to be enforced).
How can I do that?
When I try to do this:
public class Param<ValueType> where ValueType: new(){
public ValueType value = new ValueType();
}
class stops accepting strings.
When I remove new() constraint, I can no longer use new ValueType()
(obviously) and value
is null for all new instances of Param<string>
.
What can I do about it?
The reason why I want this to happen is because I have .Equals()
defined which does value.Equals(other.value)
, which causes exception to be thrown when value
is null.
Upvotes: 2
Views: 1423
Reputation: 111810
You could:
public class Param<ValueType>
{
public ValueType value = typeof(ValueType) == typeof(string) ? (ValueType)(object)string.Empty : default(ValueType);
}
note that default(int) == 0
and so on.
Ah and for the comparison, you should:
bool areEqual = EqualityComparer<ValueType>.Equals(value, other.Value);
It correctly works for null
values.
Note even that with generics, this:
if (value == null)
{
}
is perfectly valid code. Clearly it will be true only if ValueType
can be null
and is null
(so for ValueType == int
it won't ever happen)
Upvotes: 3