Nullable parameter type name

A

Andrus

My type contains constructor with nullable parameter like

public class Iandmed {
public Iandmed(DateTime? miskuup) {}
}

I tried to get its constructor parameter type name using

Type t = typeof(Iandmed);
ConstructorInfo c = t.GetConstructors()[0];
ParameterInfo p = c.GetParameters()[0];

p.ParameterType.Name returns wrong values for nullable types, in this case

"Nullable`1"

How to get exact type name:

"DateTime?"

Andrus.
 
J

Jon Skeet [C# MVP]

Andrus said:
My type contains constructor with nullable parameter like

public class Iandmed {
public Iandmed(DateTime? miskuup) {}
}

I tried to get its constructor parameter type name using

Type t = typeof(Iandmed);
ConstructorInfo c = t.GetConstructors()[0];
ParameterInfo p = c.GetParameters()[0];

p.ParameterType.Name returns wrong values for nullable types, in this case

"Nullable`1"

How to get exact type name:

"DateTime?"

Don't use the Name property - use other properties to get specific
parts. In particular, the FullName property gives
System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0,
Culture=neutral,PublicKeyToken=b77a5c561934e089]]

Alternatively you can use
p.ParameterType.GetGenericArguments()[0]

to get the DateTime part on its own, or
Nullable.GetUnderlyingType(p.ParameterType)
 
P

Peter Duniho

[...]
p.ParameterType.Name returns wrong values for nullable types, in this case

"Nullable`1"

How to get exact type name:

"DateTime?"

I don't have the answer off the top of my head. But I can tell you
that you are getting the correct type name. "DateTime?" is actually
equivalent to "Nullable<DateTime>", thus the generated generic type
name.

You'll want to research how to obtain the generic paramter type
information from a concrete instance of a generic class. That will
provide the information you're looking for. Unfortunately, I don't use
reflection enough to be able to tell you the exact answer, but
hopefully that gets you pointed in the right direction.

Pete
 

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