Bartek Chyży
Bartek Chyży

Reputation: 541

Cleaner way than Invoke anonymous method in c#

Is it better way to write this code? This way looks to be so complicated. I want to assign example value depending on anotherVariable.

var example = new Func<DateTime>((() =>
{
    switch (anotherVariable)
    {
        case "Jesus birth": return new DateTime(0, 12, 24);
        case "Second condition": return new DateTime(2017, 23, 11);
        // etc
        default: return DateTime.Now;
    }
})).Invoke();

Upvotes: 0

Views: 98

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You don't have to wrap your code in a delegate - as long as every case, including the default, assign an explicitly-typed variable, this code will work correctly:

DateTime example;
switch (anotherVariable)
{
    case "Jesus birth": example = new DateTime(0, 12, 24); break;
    case "Second condition": example = new DateTime(2017, 23, 11); break;
    // etc
    default: example = DateTime.Now; break;
}

If you insist on using a delegate, you don't need to call Invoke, because you know the type of the delegate. You can use the simple invocation syntax:

var example= (() => {
    switch (anotherVariable) {
        case "Jesus birth": return new DateTime(0,12,24); break;
        case "Second condition": return new DateTime(2017,23,11);  break;
        //another cases
        default: return DateTime.Now; break;
    }
}) ();
// ^^
// Invocation

Upvotes: 6

Related Questions