void Test<T>(T item) { if(item == default(T)) // error here ... } |
What is the reason behind this compiler error I just want to see if the item is null for reference types, or default for value types. How can I do this
void Test<T>(T item) { if(item == default(T)) // error here ... } |
How to determine if a generic parameter is null or default?
Konstantinos55265
private static readonly IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
public static bool IsDefault(T t) {
return comparer.Equals(t, default(T));
}
This way, for valuetypes *that implement IEquatable<T>* you don't get the boxing cost. For other valuetypes, the normal object.Equals(object) will be used for the comparison, which involves boxing. You also may want to allow clients of your class to specify their own IEqualityComparer<T>, like e.g. the Dictionary class does (allowing boxing-free comparison of valuetypes not implementing IEquatable<T>).
kenmc
Are you looking to have methods with default parameters filled in That does not involve the use of the default keyword. Overloading is one way to accomplish that. Such as the example given in the help files:
public void Test() { Test(9); }
public void Test(int i) {}
Craver84
if (object.Equals(item, default(T))
However, that will call Equals in the case where both parameters are non-null, which isn't ideal. If you don't mind that happening, that may be a reasonable solution. I'll see if I can work out any others though...
Jon
Tom McDonnell
timdude
My actual situation is far more complex that what I'm posting, so to simplify, what I need is this:
void Foo<T>(T item)
{
// determine if item is null (for a reference type) or default (for a value type)
}
This appears to be a limitation in .NET (or at least, C#) generics, but I'm not sure yet.
Am I clear on the problem I'm running into
Marcel de Vries
if (ReferenceEquals(t, default(T)) || Equals(t, default(T)));
Dave J Smith
Ok, I see what you are talking about now. Why not just cast to string after you know it is not null With the exception of structs, that should work.
T temp =
default(T); if (temp == null){
MessageBox.Show("Reference Type");}
else{
MessageBox.Show("Value Type"); if (temp.ToString() == item.ToString()){
MessageBox.Show("Equals Default");}
else{
MessageBox.Show("Does Not Equal Default");}
}
Frank Buckley
Here is my understanding of how to use default:
public Form1()
{
InitializeComponent();
Test(1);
Test(
this);}
private void Test<T>(T item){
T temp =
default(T); if (temp == null){
MessageBox.Show("Reference Type");}
else{
MessageBox.Show("Value Type");}
}
MikeKelly
bizhaoqi
Jon