Is there a single line quivalent for this:
void AcceptChanges() => Data != null ? DoSomethingWithData(Data);
I wonder why this has not been addressed in c# so far.
because of the void return type its also not possible to do something like this
void AcceptChanges() => Data != null ? DoSomethingWithData(Data) : null;
Would be nicer to do something like this to intend No-call
void AcceptChanges() => Data != null ? DoSomethingWithData(Data) : void;
or new meaning of ?? (as the bool-expression iitself cannot be null in this case)
void AcceptChanges() => Data != null ?? DoSomethingWithData(Data);
Edit: The closest solution for this is using a Delegate:
using System;
using System.Diagnostics.CodeAnalysis;
public static class VoidHelper
{
// ReSharper disable once UnusedParameter.Global
public static void RunVoid([NotNull] this object source, bool condition, Action action) =>
RunVoid(condition, action);
public static void RunVoid(bool condition, Action action)
{
if (condition)
action();
}
// ReSharper disable once UnusedParameter.Global
public static void RunVoid<T>([NotNull] this object source, bool condition, Action<T> action, T arg) =>
RunVoid(condition, action, arg);
public static void RunVoid<T>(bool condition, Action<T> action, T arg)
{
if (condition)
action(arg);
}
// Add more args if neccessary
public static void Test(object data) => RunVoid(data != null, () => DoSomethingWithData(data));
private static void DoSomethingWithData(object data) { }
}