Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a 'null' action

Tags:

c#

.net

I have the following function definition

private void DoExport(Action<ColumnView, bool> UpdateColumns)  
{  
...  
}

private void UpdateNonPrintableColumns(ColumnView view, bool visible)  
{  
...  
}   

Example of it being called:

DoExport(UpdateNonPrintableColumns);

My question is. How do I pass a 'null' action? Is it even possible?

e.g.
DoExport(null); <- Throws exception

DoExport(null) causes an exception to be thrown when the action gets called in the function body

like image 990
Eminem Avatar asked May 30 '14 08:05

Eminem


3 Answers

Pass in an empty action if you want to:

DoExport((x, y) => { })

Second, you have to review your code, since passing in null is perfectly fine.

public void X()
{
    A(null);
}

public void A(Action<ColumnView, bool> a)
{
    if (a != null)
    {
        a();
    }
}

Or as per C# 6 (using the null-propagation operator):

public void A(Action<ColumnView, bool> a)
{
    a?.Invoke();
}
like image 134
Patrick Hofman Avatar answered Oct 02 '22 10:10

Patrick Hofman


You can pass an action that does nothing:

DoExport((_, __) => { });
like image 33
Chris Mantle Avatar answered Oct 02 '22 12:10

Chris Mantle


Or just handle it inside of the method:

private void DoExport(Action<ColumnView, bool> UpdateColumns)  
{  
  if (UpdateColumns != null)
    UpdateColumns(...);
}
like image 45
Luaan Avatar answered Oct 02 '22 12:10

Luaan