Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lazy with instance variable

Given the code below

public class classA
{
   int someid ;
   public classA( int x ) { someid = x; }

   Lazy<myType> lazymt1 = new Lazy<myType>( 
       return MyStaticClassMethod.GetFor( someid );    // problem statement - how should this be coded ?
   );

  public myType GetMyType { return lazymt1.value ; }
}

how do I pass the variable someid and code the Func<myType>?

UPDATE - here's what I tried so far and the results

Lazy<myType> lazymt1 = new Lazy<myType>( () =>  MyStaticClassMethod.GetFor( someid ) );

The above line doesn't compile and the red squiggly line says

cannot convert lambda expression to LazyThreadSafetyMode because it's not a delegate type

like image 414
Kumar Avatar asked Sep 13 '25 04:09

Kumar


1 Answers

The simplest is probably through a lambda:

Lazy<myType> lazymt1 = new Lazy<myType>( 
       () => MyStaticClassMethod.GetFor( someid )
   );

You'll also need to initialize the Lazy object in the constructor to access the implicit object reference:

private Lazy<myType> lazymt1;

public classA()
{
    lazymt1 = new Lazy<myType>(() => MyStaticClassMethod.GetFor(someid));
}
like image 186
Servy Avatar answered Sep 15 '25 18:09

Servy