开发者

Conditional assignment using delegate

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜