2

With method signatures like:

public interface TestInterface
{
    void SampleMethodOut(out int? nullableInt);
    void SampleMethod(int? nullableInt);
}

I'm using typeof(TestInterface).GetMethods()[1].GetParameters()[0].ParameterType to get the type, and then checking IsGenericType and Nullable.GetUnderlyingType. How can I do this with the method with the out parameter?

NickL
  • 1,870
  • 2
  • 15
  • 35
  • For the one that isn't an out parameter IsGenericType is true and Nullable.GetUnderlyingType returns Int32, but for the out parameter it's false and null. – NickL Apr 05 '12 at 16:20
  • So for the non-out parameter, `ParameterType` returns `typeof(Nullable)` -- what does it return for the out parameter? – phoog Apr 05 '12 at 16:23

2 Answers2

3

Doh, ignore my previous answer.

You use Type.IsByRef, and call Type.GetElementType() if so:

var type = method.GetParameters()[0].ParameterType;
if (type.IsByRef)
{
    // Remove the ref/out-ness
    type = type.GetElementType();
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

for everyone just finding this page

c# documentation pages show a concise way of doing just that
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-to-identify-a-nullable-value-type

Console.WriteLine($"int? is {(IsNullable(typeof(int?)) ? "nullable" : "non nullable")} type");
Console.WriteLine($"int is {(IsNullable(typeof(int)) ? "nullable" : "non-nullable")} type");

bool IsNullable(Type type) => Nullable.GetUnderlyingType(type) != null;

// Output:
// int? is nullable type
// int is non-nullable type

Using reflection, this is how you get your parameter types:

typeof(MyClass).GetMethod("MyMethod").GetParameters()[0].ParameterType;
Dmitry Matveev
  • 5,320
  • 1
  • 32
  • 43