1

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

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

wonea
  • 4,783
  • 17
  • 86
  • 139
Zain Ali
  • 15,535
  • 14
  • 95
  • 108
  • I know this isn't an answer to your question but remember, the shortest code isn't always the best code. In this scenario you might be better to use a normal if statement so your code is more readable and easier to understand. – DoctorMick Jul 12 '11 at 09:41
  • I am just learning delegates.And was wondering is this possible through delegates!(just for learning) – Zain Ali Jul 12 '11 at 09:43

2 Answers2

6

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; }))();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    @Zain: I have *no* idea what that comment means. EDIT: Okay, now I've compiled it for myself... that's *not* an exception, it's a compile-time error. It's it's method name **expected**, not **excepted**. Huge difference. I've fixed it now - more brackets were needed... – Jon Skeet Jul 12 '11 at 09:46
  • I assume "excepted" is "expected" but still don't know what you mean @Zain – Smudge202 Jul 12 '11 at 09:49
  • @Smudge202: It means he tried to compile my code, and it didn't compile. He could have been significantly clearer though... – Jon Skeet Jul 12 '11 at 09:50
  • Will you please explain last 2 braces () in your code what are they doing? – Zain Ali Jul 12 '11 at 09:59
  • 2
    I can Zain, but probably won't come out well in a comment. The _false_ part of the tenary operator is a delegate... Func. If you don't add the final two bracers then what you are returning is a delegate. A delegate won't cast to a datatable, what you need is the result of the delegate. By adding the bracers you're telling the compiler to execute the delegate, which in turn returns a datatable. – Smudge202 Jul 12 '11 at 10:07
  • @Zain: They're *executing* the delegate. The type of the conditional expression is just `DataTable`, so given a `Func`, we need to execute it to get the result. – Jon Skeet Jul 12 '11 at 10:10
2

You mean something like this maybe?

Func<DataTable, DataTable> datatable = (n => {
    if (n == null)
        n = new DataTable();
    else
        n.Clear();
    return n; });
Smudge202
  • 4,689
  • 2
  • 26
  • 44