开发者

Conditional assignment using delegate

开发者 https://www.devze.com 2023-03-19 09:30 出处:网络
I want to assign to a datatable such that. If datatable is null create a new datatable else clear datatable

I want to assign to a datatable such that.

If datatable is null create a new datatable else clear datatable

The code I have written

datatable= (datatable== null) ? 
   new DataTable() :  
  delegate(){datatable.Clear(); retur开发者_高级运维n datatable;});

How this will be possible using delegates or anonymous methods? Using shortest code possible.


Well you could use delegates, but I really wouldn't. I'd just use:

if (dataTable == null)
{
    dataTable = new DataTable();
}
else
{
    dataTable.Clear();
}

That's a lot clearer in terms of what it's doing, IMO.

Here's the delegate version in all its hideousness:

dataTable = dataTable == null ? new DataTable() :
    ((Func<DataTable>)(() => { dataTable.Clear(); return dataTable; }))();


You mean something like this maybe?

Func<DataTable, DataTable> datatable = (n => {
    if (n == null)
        n = new DataTable();
    else
        n.Clear();
    return n; });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号