Determing if a Type is a specific Generic

G

Guest

Hi,
I'm in the process of upgrading an Object-Relational mapping library to .NET
2.0 and am wanting to implement support for Nullable typess.

I'm using Reflection to analyise the object that is being mapped and
building up a schema for the mapping.

This means I need a way to determine if the PropertyInfo.PropertyType is an
implementation of System.Nullable<>. I've been batting my head against this
for a while and only come up with one solution.

private static bool IsNullable(Type type)
{
if(!type.IsGenericType)
return false;

Type[] parameters = new Type[] { type.GetGenericArguments()[0] };

Type constructedType = typeof(Nullable<>).MakeGenericType(parameters);

return type == constructedType;
}

which I think is less than optimal.

Any suggestions?
 
J

Joanna Carter [TeamB]

"Nigel Sampson" <Nigel (e-mail address removed)> a écrit dans le
message de news: (e-mail address removed)...

| I'm in the process of upgrading an Object-Relational mapping library to
..NET
| 2.0 and am wanting to implement support for Nullable typess.
|
| I'm using Reflection to analyise the object that is being mapped and
| building up a schema for the mapping.
|
| This means I need a way to determine if the PropertyInfo.Property Type is
an
| implementation of System.Nullable<>. I've been batting my head against
this
| for a while and only come up with one solution.
|
| private static bool IsNullable(Type type)
| {
| if(!type.IsGenericType)
| return false;
|
| Type[] parameters = new Type[] { type.GetGenericArguments()[0] };
|
| Type constructedType = typeof(Nullable<>).MakeGenericType(parameters);
|
| return type == constructedType;
| }

Try this :

return type.IsGenericType && type.GetGenericTypeDefinition() ==
typeof(Nullable<>);

Joanna
 
G

Guest

Cheers, will try that tonight, I suspect my main issue when trying to
determine a decent method was not knowing that typeof(Nullable) and
typeof(Nullable<>) where two different types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top