Search code examples
c#wpffunctionvariablesvar

Create a variable that contains an action


I'am trying to do a variable that when I call it, that execute a code.

For example


string path1;
string path2;

bool check;

var make;// the variable in case

//other code

if(check == false)
{
 make = File.Copy(path1, path2); // the thing impossible to do
}
else
{
 make = File.Move(path1, path2);
}

make;//and here it should to run some code

This does not run the code that is contained in make.

But the code mustn't use an internal compiler, as Roslyn, because it is too slow.

I've try as this but doesn't work:

Action make = File.Copy(path1, path2);

I don't want to use a function as:

public void main()
{
  make();
}


public void make()
{
 if(check == false)
 {
  make = File.Copy(path1, path2);
 }
 else
 {
  make = File.Move(path1, path2);
 }
}

It's possible to do this? Thank


Solution

  • I think what you need is to harness the power of delegates, your goal can simply be achieved using this code:

    string path1;
    string path2;
    
    bool check;
    
    Action make = null;// the variable in case
    
    //other code
    
    if(check == false)
    {
     make = () => File.Copy(path1, path2); // the thing impossible to do
    }
    else
    {
     make = () => File.Move(path1, path2);
    }
    
    make();//and here it should to run some code