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

C#
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 :/
Posted
Updated 27-Sep-21 7:32am
Comments
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
   
You can't. When you compile:
C#
DoSomething<string?>();
DoSomething<string>();
the compiler emits:
C#
DoSomething<string>();
DoSomething<string>();
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.
   

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