Eminem
Eminem

Reputation: 7484

How do I pass a 'null' action

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

Upvotes: 10

Views: 18348

Answers (4)

l33t
l33t

Reputation: 19996

I think the most elegant answer is more or less part of the original question. Just add a private static callback that does nothing:

private static void EmptyCallback(ColumnView _, bool _)
{
}

Then, when calling the method, your intension gets pretty clear. And there will be no doubt what the compiler does under the hood (e.g. delegate allocations):

DoExport(EmptyCallback);

Upvotes: -1

Patrick Hofman
Patrick Hofman

Reputation: 157136

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();
}

Upvotes: 20

Luaan
Luaan

Reputation: 63772

Or just handle it inside of the method:

private void DoExport(Action<ColumnView, bool> UpdateColumns)  
{  
  if (UpdateColumns != null)
    UpdateColumns(...);
}

Upvotes: 2

Chris Mantle
Chris Mantle

Reputation: 6693

You can pass an action that does nothing:

DoExport((_, __) => { });

Upvotes: 10

Related Questions