A
Adam Badura
How to check if a value of generic type is null f it is not known if it
is a reference type or simple type.
Lets look at the example:
class Test<Type1, Type2> where Type1 : IEnumerable<Type2>
{
public Fun(Type1 item)
{
// a check is here needed
foreach (Type2 part in item)
{
/*...*/
}
}
}
If then I use code like:
new Test<string, char>().Fun(null);
I obviously get an exception because item used in foreach is null and cannot
be null. However if I add an if before foreach to check against null I
receive a warning (saddly I am not sure and cannot check now if the warning
is issued by Visual Studio, Code Analysys in Team Suite or Resharper) that
the code is not written very well because Type1 does not have to be a class
type.
The propsed solution o use not
if (item == null)
but rather
if (item == default(Type1))
(or something like this - I am not sure if the syntax was exactly like this)
does not work. It is good if Type1 is class type, but if it is struct type
then the check might yield true for a default value which might be
enumerable.
What I wanted was to check and for null throw ArgumentNullException. I
can achive this by catching null from foreach and rethrowing but I think it
is not an elegant solution. So I am asking. How to add that check against
null?
Adam Badura
is a reference type or simple type.
Lets look at the example:
class Test<Type1, Type2> where Type1 : IEnumerable<Type2>
{
public Fun(Type1 item)
{
// a check is here needed
foreach (Type2 part in item)
{
/*...*/
}
}
}
If then I use code like:
new Test<string, char>().Fun(null);
I obviously get an exception because item used in foreach is null and cannot
be null. However if I add an if before foreach to check against null I
receive a warning (saddly I am not sure and cannot check now if the warning
is issued by Visual Studio, Code Analysys in Team Suite or Resharper) that
the code is not written very well because Type1 does not have to be a class
type.
The propsed solution o use not
if (item == null)
but rather
if (item == default(Type1))
(or something like this - I am not sure if the syntax was exactly like this)
does not work. It is good if Type1 is class type, but if it is struct type
then the check might yield true for a default value which might be
enumerable.
What I wanted was to check and for null throw ArgumentNullException. I
can achive this by catching null from foreach and rethrowing but I think it
is not an elegant solution. So I am asking. How to add that check against
null?
Adam Badura