Alternative to switch with non-constant - c#

I just learned that a switch statement can't use non-constant conditions. Which is fine and all, I get it. But does that really mean I have to make a big if-else block? It's so ugly I'm crying.
Some context: I'm doing a Unity project and I want to switch on the current animation state. A good way to check the current animation state is to compare hashes, which means I need to calculate the hashes for the animation state. After calculating them I want to switch on them. (Writing this I realized I can paste the resulting hash into a constant, but now I still want an answer)
int state1 = Animator.StringToHash("State1");
int state2 = Animator.StringToHash("State2");
int hash = _myAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash;
switch (hash):
{
case state1:
//DoStuff
break;
case state2:
//Other stuff
break;
}
What's the best way to do this?

You can do this with a dictionary.
Try this:
int state1 = Animator.StringToHash("State1");
int state2 = Animator.StringToHash("State2");
int hash = _myAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash;
var cases = new Dictionary<Func<bool>, Action>()
{
{ () => hash == state1, () => { /* Do stuff */} },
{ () => hash == state2, () => { /* Do other stuff */} },
};
cases
.Where(c => c.Key()) // find conditions that match
.Select(kvp => kvp.Value) //select the `Action`
.FirstOrDefault() // take only the first one
?.Invoke(); // Invoke the action only if not `null`
To make it a little more clean you could define a Switch class like this:
public class Switch : IEnumerable<Switch.Case>
{
private List<Case> _list = new List<Case>();
public void Add(Func<bool> condition, Action action)
{
_list.Add(new Case(condition, action));
}
IEnumerator<Case> IEnumerable<Case>.GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
public void Execute()
{
this
.Where(c => c.Condition())
.Select(c => c.Action)
.FirstOrDefault()
?.Invoke();
}
public sealed class Case
{
private readonly Func<bool> _condition;
private readonly Action _action;
public Func<bool> Condition { get { return _condition; } }
public Action Action { get { return _action; } }
public Case(Func<bool> condition, Action action)
{
_condition = condition;
_action = action;
}
}
}
Then the code looks like this:
int state1 = Animator.StringToHash("State1");
int state2 = Animator.StringToHash("State2");
int hash = _myAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash;
var #switch = new Switch()
{
{ () => hash == state1, () => { /* Do stuff */} },
{ () => hash == state2, () => { /* Do other stuff */} },
};
#switch.Execute();
And if you write it like this it almost looks like a normal switch statement:
var #switch = new Switch()
{
{
() => hash == state1,
() =>
{
/* Do stuff */
}
},
{
() => hash == state2,
() =>
{
/* Do other stuff */
}
},
};

You can also use case guards and local functions like this:
bool HashMatches(int TargetHash) => hash == TargetHash;
switch (true):
{
case true when HashMatches(state1):
//DoStuff
break;
case true when HashMatches(state2):
//Other stuff
break;
}

Whether you can simplify it or not, it depends on the similarities between your "DoStuff", "Other Stuff", "Next Stuff", and "You other stuffs"
Suppose your Stuff "family members" are actually:
int stuffAction(int state){
int modified_state;
//do something on state and modified state
return modified_state;
}
Then, obviously you Stuffs can be simplified by using function, just as shown above. It can be simplified likewise as long as your Stuff have same function with different argument.
Also, if you Stuffs are in the form different functions but having the same input parameters, you can create Dictionary of delegates (see System.Collections.Generic.Dictionary<string, System.Delegate>) such that when you can call the Stuff you simply need to do
dic[state](input parameters here)
instead of using if-else or switch
There might be some possibilities where your code cannot be simplified further, but the bottom line is, as I said earlier, depend on the similarities between your Stuffs.

You can do it only with if-else if:
int state1 = Animator.StringToHash("State1");
int state2 = Animator.StringToHash("State2");
int hash = _myAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash;
if (hash == state1) {
//DoStuff
}
else if (hash == state2) {
//Other stuff
}

Related

How to make an empty default case in switch expression in C#?

How to make an empty default case in switch expression in C#?
I am talking about this language feature.
Here is what I am trying:
using System;
public class Program
{
public static void Main()
{
int i = -2;
var ignore = i switch {
-1 => Console.WriteLine("foo"),
-2 => Console.WriteLine("bar"),
_ => ,
};
}
}
Also, I tried without the comma:
using System;
public class Program
{
public static void Main()
{
int i = -2;
var ignore = i switch {
-1 => Console.WriteLine("foo"),
-2 => Console.WriteLine("bar"),
_ =>
};
}
}
Still it does not want to compile. So, I tried to put an empty function:
using System;
public class Program
{
public static void Main()
{
int i = -2;
var ignore = i switch {
-1 => Console.WriteLine("foo"),
-2 => Console.WriteLine("bar"),
_ => {}
};
}
}
And it still does not work.
You are studing expressions switch expressions to be exact. All expressions must return a value; while Console.WriteLine being of type void returns nothing.
To fiddle with switch expressions you can try
public static void Main() {
int i = -2;
// switch expression: given i (int) it returns text (string)
var text = i switch {
-1 => "foo",
-2 => "ignore",
_ => "???" // or default, string.Empty etc.
};
Console.WriteLine(text);
}
Or putting expression into WriteLine:
public static void Main() {
int i = -2;
// switch expression returns text which is printed by WriteLine
Console.WriteLine(i switch {
-1 => "foo",
-2 => "ignore",
_ => "???"
});
}
A switch expression must be able to evaluate to a value, as with all expressions.
For your purpose, a switch statement is the correct construct:
int i = -2;
switch (i)
{
case -1:
Console.WriteLine("foo");
break;
case -2:
Console.WriteLine("bar");
break;
}

How to check multiple properties on an object have the same condition?

I have a pretty long and unwieldy method which takes in an object as a parameter, then checks every property against the same criteria (== "random") and performs a specific action against the property.
public void CreateRegistration(UserGroup user, int mobileLength, int passwordLength, int questionLength) {
if (user.Title == "random") {
title.ClickDropdown();
} else {
WebElementExtensions.ClickDropdown(title,user.Title);
}
if (user.Firstname == "random") {
firstName.SendKeys(GenerateData.GenerateRandomName());
} else {
firstName.SendKeys(user.Firstname);
}
if (user.Middlename == "random") {
middleName.SendKeys(GenerateData.GenerateRandomName());
} else {
firstName.SendKeys(user.Middlename);
}
etc....
Is it possible to somehow check all my properties against the same criteria together, then reduce my code so all the actions on the individual properties are within the same code block? so one code block for is = random and one for else.
Many thanks,
I prefer to use LINQ for this purpose usually:
private bool CheckAllProperties(UserGroup instance)
{
return instance.GetType().GetProperties()
.Where(c => c.GetValue(instance) is string)
.Select(c => (string)c.GetValue(instance))
.All(c => c== "random");
}
And then:
if (CheckAllProperties(user))
{
}

Why there is no expression sequencing operator? [duplicate]

I'm using some functional stuff in C# and keep getting stuck on the fact that List.Add doesn't return the updated list.
In general, I'd like to call a function on an object and then return the updated object.
For example it would be great if C# had a comma operator:
((accum, data) => accum.Add(data), accum)
I could write my own "comma operator" like this:
static T comma(Action a, Func<T> result) {
a();
return result();
}
It looks like it would work but the call site would ugly. My first example would be something like:
((accum, data) => comma(accum.Add(data), ()=>accum))
Enough examples! What's the cleanest way to do this without another developer coming along later and wrinkling his or her nose at the code smell?
I know this as Fluent.
A Fluent example of a List.Add using Extension Methods
static List<T> MyAdd<T>(this List<T> list, T element)
{
list.Add(element);
return list;
}
I know that this thread is very old, but I want to append the following information for future users:
There isn't currently such an operator. During the C# 6 development cycle a semicolon operator was added, as:
int square = (int x = int.Parse(Console.ReadLine()); Console.WriteLine(x - 2); x * x);
which can be translated as follows:
int square = compiler_generated_Function();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int compiler_generated_Function()
{
int x = int.Parse(Console.ReadLine());
Console.WriteLine(x - 2);
return x * x;
}
However, this feature was dropped before the final C# release.
You can do almost exactly the first example naturally using code blocks in C# 3.0.
((accum, data) => { accum.Add(data); return accum; })
This is what Concat http://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx is for. Just wrap a single item in an array. Functional code should not mutate the original data. If performance is a concern, and this isn't good enough, then you'll no longer be using the functional paradigm.
((accum, data) => accum.Concat(new[]{data}))
Another technique, straight from functional programming, is as follows. Define an IO struct like this:
/// <summary>TODO</summary>
public struct IO<TSource> : IEquatable<IO<TSource>> {
/// <summary>Create a new instance of the class.</summary>
public IO(Func<TSource> functor) : this() { _functor = functor; }
/// <summary>Invokes the internal functor, returning the result.</summary>
public TSource Invoke() => (_functor | Default)();
/// <summary>Returns true exactly when the contained functor is not null.</summary>
public bool HasValue => _functor != null;
X<Func<TSource>> _functor { get; }
static Func<TSource> Default => null;
}
and make it a LINQ-able monad with these extension methods:
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class IO {
public static IO<TSource> ToIO<TSource>( this Func<TSource> source) {
source.ContractedNotNull(nameof(source));
return new IO<TSource>(source);
}
public static IO<TResult> Select<TSource,TResult>(this IO<TSource> #this,
Func<TSource,TResult> projector
) =>
#this.HasValue && projector!=null
? New(() => projector(#this.Invoke()))
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,TResult>(this IO<TSource> #this,
Func<TSource,IO<TResult>> selector
) =>
#this.HasValue && selector!=null
? New(() => selector(#this.Invoke()).Invoke())
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,T,TResult>(this IO<TSource> #this,
Func<TSource, IO<T>> selector,
Func<TSource,T,TResult> projector
) =>
#this.HasValue && selector!=null && projector!=null
? New(() => { var s = #this.Invoke(); return projector(s, selector(s).Invoke()); } )
: Null<TResult>();
public static IO<TResult> New<TResult> (Func<TResult> functor) => new IO<TResult>(functor);
private static IO<TResult> Null<TResult>() => new IO<TResult>(null);
}
and now you can use the LINQ comprehensive syntax thus:
using Xunit;
[Fact]
public static void IOTest() {
bool isExecuted1 = false;
bool isExecuted2 = false;
bool isExecuted3 = false;
bool isExecuted4 = false;
IO<int> one = new IO<int>( () => { isExecuted1 = true; return 1; });
IO<int> two = new IO<int>( () => { isExecuted2 = true; return 2; });
Func<int, IO<int>> addOne = x => { isExecuted3 = true; return (x + 1).ToIO(); };
Func<int, Func<int, IO<int>>> add = x => y => { isExecuted4 = true; return (x + y).ToIO(); };
var query1 = ( from x in one
from y in two
from z in addOne(y)
from _ in "abc".ToIO()
let addOne2 = add(x)
select addOne2(z)
);
Assert.False(isExecuted1); // Laziness.
Assert.False(isExecuted2); // Laziness.
Assert.False(isExecuted3); // Laziness.
Assert.False(isExecuted4); // Laziness.
int lhs = 1 + 2 + 1;
int rhs = query1.Invoke().Invoke();
Assert.Equal(lhs, rhs); // Execution.
Assert.True(isExecuted1);
Assert.True(isExecuted2);
Assert.True(isExecuted3);
Assert.True(isExecuted4);
}
When one desires an IO monad that composes but returns only void, define this struct and dependent methods:
public struct Unit : IEquatable<Unit>, IComparable<Unit> {
[CLSCompliant(false)]
public static Unit _ { get { return _this; } } static Unit _this = new Unit();
}
public static IO<Unit> ConsoleWrite(object arg) =>
ReturnIOUnit(() => Write(arg));
public static IO<Unit> ConsoleWriteLine(string value) =>
ReturnIOUnit(() => WriteLine(value));
public static IO<ConsoleKeyInfo> ConsoleReadKey() => new IO<ConsoleKeyInfo>(() => ReadKey());
which readily allow the writing of code fragments like this:
from pass in Enumerable.Range(0, int.MaxValue)
let counter = Readers.Counter(0)
select ( from state in gcdStartStates
where _predicate(pass, counter())
select state )
into enumerable
where ( from _ in Gcd.Run(enumerable.ToList()).ToIO()
from __ in ConsoleWrite(Prompt(mode))
from c in ConsoleReadKey()
from ___ in ConsoleWriteLine()
select c.KeyChar.ToUpper() == 'Q'
).Invoke()
select 0;
where the old C comma operator is readily recognized for what it is: a monadic compose operation.
The true merit of the comprehension syntax is apparent when one attempts to write that fragment in the flunt style:
( Enumerable.Range(0,int.MaxValue)
.Select(pass => new {pass, counter = Readers.Counter(0)})
.Select(_ => gcdStartStates.Where(state => _predicate(_.pass,_.counter()))
.Select(state => state)
)
).Where(enumerable =>
( (Gcd.Run(enumerable.ToList()) ).ToIO()
.SelectMany(_ => ConsoleWrite(Prompt(mode)),(_,__) => new {})
.SelectMany(_ => ConsoleReadKey(), (_, c) => new {c})
.SelectMany(_ => ConsoleWriteLine(), (_,__) => _.c.KeyChar.ToUpper() == 'Q')
).Invoke()
).Select(list => 0);
The extension method is arguably the best solution, but for completeness' sake, don't forget the obvious alternative: a wrapper class.
public class FList<T> : List<T>
{
public new FList<T> Add(T item)
{
base.Add(item);
return this;
}
public new FList<T> RemoveAt(int index)
{
base.RemoveAt(index);
return this;
}
// etc...
}
{
var list = new FList<string>();
list.Add("foo").Add("remove me").Add("bar").RemoveAt(1);
}
I thought it would be interesting to make a version of my wrapper class answer that doesn't require you write the wrapper methods.
public class FList<T> : List<T>
{
public FList<T> Do(string method, params object[] args)
{
var methodInfo = GetType().GetMethod(method);
if (methodInfo == null)
throw new InvalidOperationException("I have no " + method + " method.");
if (methodInfo.ReturnType != typeof(void))
throw new InvalidOperationException("I'm only meant for void methods.");
methodInfo.Invoke(this, args);
return this;
}
}
{
var list = new FList<string>();
list.Do("Add", "foo")
.Do("Add", "remove me")
.Do("Add", "bar")
.Do("RemoveAt", 1)
.Do("Insert", 1, "replacement");
foreach (var item in list)
Console.WriteLine(item);
}
Output:
foo
replacement
bar
EDIT
You can slim down the syntax by exploiting C# indexed properties.
Simply add this method:
public FList<T> this[string method, params object[] args]
{
get { return Do(method, args); }
}
And the call now looks like:
list = list["Add", "foo"]
["Add", "remove me"]
["Add", "bar"]
["RemoveAt", 1]
["Insert", 1, "replacement"];
With the linebreaks being optional, of course.
Just a bit of fun hacking the syntax.

Is there idiomatic C# equivalent to C's comma operator?

I'm using some functional stuff in C# and keep getting stuck on the fact that List.Add doesn't return the updated list.
In general, I'd like to call a function on an object and then return the updated object.
For example it would be great if C# had a comma operator:
((accum, data) => accum.Add(data), accum)
I could write my own "comma operator" like this:
static T comma(Action a, Func<T> result) {
a();
return result();
}
It looks like it would work but the call site would ugly. My first example would be something like:
((accum, data) => comma(accum.Add(data), ()=>accum))
Enough examples! What's the cleanest way to do this without another developer coming along later and wrinkling his or her nose at the code smell?
I know this as Fluent.
A Fluent example of a List.Add using Extension Methods
static List<T> MyAdd<T>(this List<T> list, T element)
{
list.Add(element);
return list;
}
I know that this thread is very old, but I want to append the following information for future users:
There isn't currently such an operator. During the C# 6 development cycle a semicolon operator was added, as:
int square = (int x = int.Parse(Console.ReadLine()); Console.WriteLine(x - 2); x * x);
which can be translated as follows:
int square = compiler_generated_Function();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int compiler_generated_Function()
{
int x = int.Parse(Console.ReadLine());
Console.WriteLine(x - 2);
return x * x;
}
However, this feature was dropped before the final C# release.
You can do almost exactly the first example naturally using code blocks in C# 3.0.
((accum, data) => { accum.Add(data); return accum; })
This is what Concat http://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx is for. Just wrap a single item in an array. Functional code should not mutate the original data. If performance is a concern, and this isn't good enough, then you'll no longer be using the functional paradigm.
((accum, data) => accum.Concat(new[]{data}))
Another technique, straight from functional programming, is as follows. Define an IO struct like this:
/// <summary>TODO</summary>
public struct IO<TSource> : IEquatable<IO<TSource>> {
/// <summary>Create a new instance of the class.</summary>
public IO(Func<TSource> functor) : this() { _functor = functor; }
/// <summary>Invokes the internal functor, returning the result.</summary>
public TSource Invoke() => (_functor | Default)();
/// <summary>Returns true exactly when the contained functor is not null.</summary>
public bool HasValue => _functor != null;
X<Func<TSource>> _functor { get; }
static Func<TSource> Default => null;
}
and make it a LINQ-able monad with these extension methods:
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class IO {
public static IO<TSource> ToIO<TSource>( this Func<TSource> source) {
source.ContractedNotNull(nameof(source));
return new IO<TSource>(source);
}
public static IO<TResult> Select<TSource,TResult>(this IO<TSource> #this,
Func<TSource,TResult> projector
) =>
#this.HasValue && projector!=null
? New(() => projector(#this.Invoke()))
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,TResult>(this IO<TSource> #this,
Func<TSource,IO<TResult>> selector
) =>
#this.HasValue && selector!=null
? New(() => selector(#this.Invoke()).Invoke())
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,T,TResult>(this IO<TSource> #this,
Func<TSource, IO<T>> selector,
Func<TSource,T,TResult> projector
) =>
#this.HasValue && selector!=null && projector!=null
? New(() => { var s = #this.Invoke(); return projector(s, selector(s).Invoke()); } )
: Null<TResult>();
public static IO<TResult> New<TResult> (Func<TResult> functor) => new IO<TResult>(functor);
private static IO<TResult> Null<TResult>() => new IO<TResult>(null);
}
and now you can use the LINQ comprehensive syntax thus:
using Xunit;
[Fact]
public static void IOTest() {
bool isExecuted1 = false;
bool isExecuted2 = false;
bool isExecuted3 = false;
bool isExecuted4 = false;
IO<int> one = new IO<int>( () => { isExecuted1 = true; return 1; });
IO<int> two = new IO<int>( () => { isExecuted2 = true; return 2; });
Func<int, IO<int>> addOne = x => { isExecuted3 = true; return (x + 1).ToIO(); };
Func<int, Func<int, IO<int>>> add = x => y => { isExecuted4 = true; return (x + y).ToIO(); };
var query1 = ( from x in one
from y in two
from z in addOne(y)
from _ in "abc".ToIO()
let addOne2 = add(x)
select addOne2(z)
);
Assert.False(isExecuted1); // Laziness.
Assert.False(isExecuted2); // Laziness.
Assert.False(isExecuted3); // Laziness.
Assert.False(isExecuted4); // Laziness.
int lhs = 1 + 2 + 1;
int rhs = query1.Invoke().Invoke();
Assert.Equal(lhs, rhs); // Execution.
Assert.True(isExecuted1);
Assert.True(isExecuted2);
Assert.True(isExecuted3);
Assert.True(isExecuted4);
}
When one desires an IO monad that composes but returns only void, define this struct and dependent methods:
public struct Unit : IEquatable<Unit>, IComparable<Unit> {
[CLSCompliant(false)]
public static Unit _ { get { return _this; } } static Unit _this = new Unit();
}
public static IO<Unit> ConsoleWrite(object arg) =>
ReturnIOUnit(() => Write(arg));
public static IO<Unit> ConsoleWriteLine(string value) =>
ReturnIOUnit(() => WriteLine(value));
public static IO<ConsoleKeyInfo> ConsoleReadKey() => new IO<ConsoleKeyInfo>(() => ReadKey());
which readily allow the writing of code fragments like this:
from pass in Enumerable.Range(0, int.MaxValue)
let counter = Readers.Counter(0)
select ( from state in gcdStartStates
where _predicate(pass, counter())
select state )
into enumerable
where ( from _ in Gcd.Run(enumerable.ToList()).ToIO()
from __ in ConsoleWrite(Prompt(mode))
from c in ConsoleReadKey()
from ___ in ConsoleWriteLine()
select c.KeyChar.ToUpper() == 'Q'
).Invoke()
select 0;
where the old C comma operator is readily recognized for what it is: a monadic compose operation.
The true merit of the comprehension syntax is apparent when one attempts to write that fragment in the flunt style:
( Enumerable.Range(0,int.MaxValue)
.Select(pass => new {pass, counter = Readers.Counter(0)})
.Select(_ => gcdStartStates.Where(state => _predicate(_.pass,_.counter()))
.Select(state => state)
)
).Where(enumerable =>
( (Gcd.Run(enumerable.ToList()) ).ToIO()
.SelectMany(_ => ConsoleWrite(Prompt(mode)),(_,__) => new {})
.SelectMany(_ => ConsoleReadKey(), (_, c) => new {c})
.SelectMany(_ => ConsoleWriteLine(), (_,__) => _.c.KeyChar.ToUpper() == 'Q')
).Invoke()
).Select(list => 0);
The extension method is arguably the best solution, but for completeness' sake, don't forget the obvious alternative: a wrapper class.
public class FList<T> : List<T>
{
public new FList<T> Add(T item)
{
base.Add(item);
return this;
}
public new FList<T> RemoveAt(int index)
{
base.RemoveAt(index);
return this;
}
// etc...
}
{
var list = new FList<string>();
list.Add("foo").Add("remove me").Add("bar").RemoveAt(1);
}
I thought it would be interesting to make a version of my wrapper class answer that doesn't require you write the wrapper methods.
public class FList<T> : List<T>
{
public FList<T> Do(string method, params object[] args)
{
var methodInfo = GetType().GetMethod(method);
if (methodInfo == null)
throw new InvalidOperationException("I have no " + method + " method.");
if (methodInfo.ReturnType != typeof(void))
throw new InvalidOperationException("I'm only meant for void methods.");
methodInfo.Invoke(this, args);
return this;
}
}
{
var list = new FList<string>();
list.Do("Add", "foo")
.Do("Add", "remove me")
.Do("Add", "bar")
.Do("RemoveAt", 1)
.Do("Insert", 1, "replacement");
foreach (var item in list)
Console.WriteLine(item);
}
Output:
foo
replacement
bar
EDIT
You can slim down the syntax by exploiting C# indexed properties.
Simply add this method:
public FList<T> this[string method, params object[] args]
{
get { return Do(method, args); }
}
And the call now looks like:
list = list["Add", "foo"]
["Add", "remove me"]
["Add", "bar"]
["RemoveAt", 1]
["Insert", 1, "replacement"];
With the linebreaks being optional, of course.
Just a bit of fun hacking the syntax.

Is there a way to specify an "empty" C# lambda expression?

I'd like to declare an "empty" lambda expression that does, well, nothing.
Is there a way to do something like this without needing the DoNothing() method?
public MyViewModel()
{
SomeMenuCommand = new RelayCommand(
x => DoNothing(),
x => CanSomeMenuCommandExecute());
}
private void DoNothing()
{
}
private bool CanSomeMenuCommandExecute()
{
// this depends on my mood
}
My intent in doing this is only control the enabled/disabled state of my WPF command, but that's an aside. Maybe it's just too early in the morning for me, but I imagine there must be a way to just declare the x => DoNothing() lambda expression in some way like this to accomplish the same thing:
SomeMenuCommand = new RelayCommand(
x => (),
x => CanSomeMenuCommandExecute());
Is there some way to do this? It just seems unnecessary to need a do-nothing method.
Action doNothing = () => { };
I thought I would add some code that I've found useful for this type of situation. I have an Actions static class and a Functions static class with some basic functions in them:
public static class Actions
{
public static void Empty() { }
public static void Empty<T>(T value) { }
public static void Empty<T1, T2>(T1 value1, T2 value2) { }
/* Put as many overloads as you want */
}
public static class Functions
{
public static T Identity<T>(T value) { return value; }
public static T0 Default<T0>() { return default(T0); }
public static T0 Default<T1, T0>(T1 value1) { return default(T0); }
/* Put as many overloads as you want */
/* Some other potential methods */
public static bool IsNull<T>(T entity) where T : class { return entity == null; }
public static bool IsNonNull<T>(T entity) where T : class { return entity != null; }
/* Put as many overloads for True and False as you want */
public static bool True<T>(T entity) { return true; }
public static bool False<T>(T entity) { return false; }
}
I believe this helps improve readability just a tiny bit:
SomeMenuCommand = new RelayCommand(
Actions.Empty,
x => CanSomeMenuCommandExecute());
// Another example:
var lOrderedStrings = GetCollectionOfStrings().OrderBy(Functions.Identity);
This should work:
SomeMenuCommand = new RelayCommand(
x => {},
x => CanSomeMenuCommandExecute());
Assuming you only need a delegate (rather than an expression tree) then this should work:
SomeMenuCommand = new RelayCommand(
x => {},
x => CanSomeMenuCommandExecute());
(That won't work with expression trees as it's got a statement body. See section 4.6 of the C# 3.0 spec for more details.)
I don't fully understand why do you need a DoNothing method.
Can't you just do:
SomeMenuCommand = new RelayCommand(
null,
x => CanSomeMenuCommandExecute());
Action DoNothing = delegate { };
Action DoNothing2 = () => {};
I used to initialize Events to a do nothing action so it was not null and if it was called without subscription it would default to the 'do nothing function' instead of a null-pointer exception.
public event EventHandler<MyHandlerInfo> MyHandlerInfo = delegate { };
Starting with C# 9.0 you can specify discards _ for required parameters. Example:
Action<int, string, DateTime> action = (_, _, _) => { };

Categories

Resources