ryudice
ryudice

Reputation: 37366

How to get string type for nullable types

I'm generating a T4 template using the properties of my data class generated from my dbml files. To get the property type of the classes I use item.PropertyType.Name, the problem is that with nullable types it returns Nullable ``1, is there a way to getNullablefor example, orint?`?

Upvotes: 4

Views: 2270

Answers (3)

Zach Johnson
Zach Johnson

Reputation: 24232

Take a look at this other question. Marc Gravell's answer there will tell you how to get the type of the generic arguments.

Upvotes: 0

Josh
Josh

Reputation: 69262

GetGenericArguments is the method you want.

if (item.PropertyType.IsGenericType) {
    if (item.PropertyType.GetGenericType() == typeof(Nullable<>)) {
        var valueType = item.PropertyType.GetGenericArguments()[0];
    }
}

On second thought though, Darren's answer is much simpler in this case as it will return null when you pass in a non-nullable type.

Upvotes: 7

Darren Kopp
Darren Kopp

Reputation: 77627

int? === Nullable<int>. they are one in the same. If you want to know that what type the nullable is, then you can use Nullable.GetUnderlyingType(typeof(int?)) method to get the type (in this instance int)

Nullable.GetUnderlyingType

Upvotes: 11

Related Questions