1

Quick question - is there any 'prettier' way to determine if a variable was lazily initialized than:

var paramType = param.GetType();
if (paramType.FullName.Contains("System.Lazy")) 
{
    ...
}

I know it's not something really recommended to be checked, but there is a particular need to differentiate it.

brovar
  • 811
  • 4
  • 10
  • 25
  • Define "prettier". You could use something like `typeof(Lazy<>).IsAssignableFrom(param.GetType())`? See https://stackoverflow.com/questions/5461295/using-isassignablefrom-with-open-generic-types – CodeCaster Aug 28 '19 at 13:35
  • @CodeCaster That returns false – Haytam Aug 28 '19 at 13:37
  • 1
    @Haytam I know, therefore I link to a question that properly handles open generic types. – CodeCaster Aug 28 '19 at 13:38
  • Can you say more about your particular need? there may be a better way to solve the real problem. This smells like an xy problem. – Eric Lippert Aug 28 '19 at 14:08

3 Answers3

2

Try this:

if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(Lazy<>))

It should return true if param is a Lazy<T> (and paramType is param.GetType()).

mm8
  • 163,881
  • 10
  • 57
  • 88
1

You could compare the generic definition of your param instead:

Lazy<int> test = new Lazy<int>();
Console.WriteLine(typeof(Lazy<>) == test.GetType().GetGenericTypeDefinition());

You might want to hold on to the typeof(Lazy<>) in a static variable.

Haytam
  • 4,643
  • 2
  • 20
  • 43
0

The two edge cases here are when the type is not a constructed generic type, and when the type is subtype of of Lazy. So something like

typeof(Lazy<>).IsAssignableFrom(paramType.IsConstructedGenericType?paramType.GetGenericTypeDefinition():null);
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67