Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I have a method like that:

void DoSomething<T>() {
  // do some validation on `T`

How could I know and differentiate at runtime if T is, say, string, or string? ?

With value type its easy, typeof(T), is either int or Nullable<int>, which are easy to differentiate.

But for string and string? I cant find any difference at runtime... :/

What I have tried:

I tried using the debugger to look at typeof(T) and also at the MethodInfo of Fooz. Both no luck :/
Updated 27-Sep-21 6:32am
Super Lloyd 27-Sep-21 12:14pm    
nullable reference of course, is a new C# 9 feature.
Super Lloyd 27-Sep-21 12:25pm    
for the record I try to implement

public class MyList<T> : IList<t>, IList

And it's very hard to implement IList.Add(object? o), I dunno if the current implementation supports null or not..

mm... after consideration, and seemingly no possibility to get the desired info, I decided to simply reject null value in the non generic (IList) version
Share this answer
You can't. When you compile:
the compiler emits:
So the nullability of the type parameter is lost.

You could add a notnull constraint to the type parameter if it should never accept null. But without it, you can't differentiate between nullable and non-nullable reference types.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900