enumerating over all bools - c#

Not exactly a big deal to do this one myself, but I am curious if C# gives this to me anywhere:
public static IEnumerable<bool> AllBools {
get {
yield return false;
yield return true;
}
}

Here's the code, a bit clunkier than you probably want, but it works:
public static IEnumerable<bool> BoolValues {
get {
return new bool[]{true, false};
}
}
Edit: if you want code to enumerate over all values of an enum (which would be a lot more useful, imo), here is also the code:
public enum TrueOrFalse
{
True,
False
}
public static IEnumerable<TrueOrFalse> BoolValues {
get {
List<TrueOrFalse> allValues = new List<TrueOrFalse>();
foreach (var value in Enum.GetValues(typeof(TrueOrFalse))){
allValues.Add((TrueOrFalse)(value));
}
return allValues.AsEnumerable();
}
}
Even simpler, as found here (How to get an array of all enum values in C#?):
List<TrueOrFalse> valuesAsList = Enum.GetValues(typeof(TrueOrFalse)).Cast<TrueOrFalse>().ToList();

Related

How to return a named tuple with only one field

I wrote a function in c# which initially returned a named tuple.
But now, I only need one field of this tuple and I would like to keep the name because it helps me to understand my code.
private static (bool informationAboutTheExecution, bool field2thatIdontNeedAnymore) doSomething() {
// do something
return (true, false);
}
This function compile. But It's the following function that I want
private static (bool informationAboutTheExecution) doSomething() {
// do something
return (true);
}
the error messages:
Tuple must containt at least two elements
cannot implcitly convvert type 'bool' to '(informationAboutTheExecution,?)
Has somebody a solution to keep the name of the returned value?
I just want to add another option, althought he out is the easiest workaround and Marc explained already why it's not possible. I would simply create a class for it:
public class ExecutionResult
{
public bool InformationAboutTheExecution { get; set; }
}
private static ExecutionResult DoSomething()
{
// do something
return new ExecutionResult{ InformationAboutTheExecution = true };
}
The class can be extended easily and you could also ensure that it's never null and can be created with factory methods like these for example:
public class SuccessfulExecution: ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult{ InformationAboutTheExecution = true };
}
public class FailedExecution : ExecutionResult
{
public static ExecutionResult Create() => new ExecutionResult { InformationAboutTheExecution = false };
}
Now you can write code like this:
private static ExecutionResult DoSomething()
{
// do something
return SuccessfulExecution.Create();
}
and in case of an error(for example) you can add a ErrorMesage property:
private static ExecutionResult DoSomething()
{
try
{
// do something
return SuccessfulExecution.Create();
}
catch(Exception ex)
{
// build your error-message here and log it also
return FailedExecution.Create(errorMessage);
}
}
You cannot, basically. You can return a ValueTuple<bool>, but that doesn't have names. You can't add [return:TupleElementNamesAttribute] manually, as the compiler explicitly does not let you (CS8138). You could just return bool. You can do the following, but it isn't any more helpful than just returning bool:
private static ValueTuple<bool> doSomething()
=> new ValueTuple<bool>(true);
Part of the problem is that ({some expression}) is already a valid expression before value-tuple syntax was introduced, which is why
private static ValueTuple<bool> doSomething()
=> (true);
is not allowed.
If you must name your return, you can do this:
private static void doSomething(out bool information) {
// do something
information = true;
}
then call it with
bool result;
doSomething(out result);

C# - Implicitly convert or infer generic return type

I've started using the pattern of a generic result type as a wrapper object that includes a return value and information about the operation like whether it succeeded. Here's an example:
public class Researcher
{
public Result<string> LearnThing(bool factDesired)
{
// Validate and bail if failure
var validationResult = ValidateIntentions(factDesired);
if (!validationResult.Succeeded)
{
// Ideally: return validationResult directly without converting to new instance
return Result.Failure<string>(validationResult.Error);
}
return StateOpinion();
}
public Result<string> StateOpinion()
{
return Result.Success("I like turtles");
}
public Result<bool> ValidateIntentions(bool factDesired)
{
if (factDesired)
{
// Ideally: no <bool> required, infer default instead
return Result.Failure<bool>("Only opinions here, sorry");
}
else
{
return Result.Success(true);
}
}
}
public class Result<T>
{
public bool Succeeded { get; set; }
public string Error { get; set; }
public T Value { get; set; }
}
// Static helpers
public static class Result
{
public static Result<T> Success<T>(T value)
{
return new Result<T> { Succeeded = true, Value = value };
}
public static Result<T> Failure<T>(string error)
{
return new Result<T> { Succeeded = false, Error = error };
}
}
Here, the generic Result<T> class is used on each method and a static helper class provides a mechanism to create the results with success status implied. So far, this is working nicely.
The one bikeshedding annoyance I have with this approach is that I need to restate the <T> often where ideally it could be inferred or when I no longer care about T Value (which would be default) and only about Error, as in the case of failures. I somewhat understand that C# doesn't infer from method return types, but I have come across some mentions of implicit operators that seem to allow some cool tricks that I don't quite understand.
So, I humbly submit the question to the C# wizards among you: is there some variation or magic I can add to this approach to achieve more type inference and effectively an implicit Result<"I don't care"> for failure results?
You can use exactly the same technique as described in the article you linked to.
Step 1: You define a non-generic helper class for your Failure case:
public class FailureResult
{
public string Error { get; }
public FailureResult(string error) { Error = error; }
}
Step 2: You change your static helper to return a FailureResult instead of a Result<T>:
public static class Result
{
...
public static FailureResult Failure(string error)
{
return new FailureResult(error);
}
}
Step 3: You define an implicit conversion from FailureResult to Result<T>:
public class Result<T>
{
...
public static implicit operator Result<T>(FailureResult result)
{
return new Result<T> { Succeeded = false, Error = result.Error };
}
}
Step 4: Profit
public Result<bool> ValidateIntentions(bool factDesired)
{
if (factDesired)
{
// No <bool> required!
return Result.Failure("Only opinions here, sorry");
}
else
{
return Result.Success(true);
}
}
(fiddle)
You could get around the bool issue with just an overload:
public static Result<bool> Failure(string error)
{
return new Result<bool> { Succeeded = false, Error = error };
}
Allowing this:
return Result.Failure("Only opinions here, sorry");
As for:
// Ideally: return validationResult directly without converting to new instance
return Result.Failure<string>(validationResult.Error);
You could use an implicit operator:
public static implicit operator Result<string>(Result<T> result)
{
return Result.Failure<string>(result.Error);
}
Which would allow you to do:
if (!validationResult.Succeeded)
{
// Ideally: return validationResult directly without converting to new instance
return validationResult;
}
Though I personally wouldn't do this, it's unexpected and misusing the language feature.
You could however use an instance method or extension method:
public Result<string> AsError()
{
return Result.Failure<string>(Error);
}
In all honesty, I think what you have is declarative and not trying to be magic. I would just stick with some helper (extension) methods if need be.
Maybe something like this:
public class Result<T>
{
public bool Succeeded { get; set; }
public string Error { get; set; }
public T Value { get; set; }
public bool HasValue { get; protected set; } = true;
}
public class Result : Result<object>
{
public Result() { HasValue = false; }
}
public static class ResultFactory
{
public static Result<T> Success<T>(T value)
{
return new Result<T> { Succeeded = true, Value = value };
}
public static Result Success()
{
return new Result { Succeeded = true };
}
public static Result Failure(string error)
{
return new Result { Succeeded = false, Error = error };
}
}
This allows you not to have to "kludge" in a bool somewhere to to make it fit your pattern. Sure you are creating a null object, but that is more-or-less tucked away.

I've got two functions that differ only by some condition. Can it be unified?

So I have these two methods:
public static string Figure2D()
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (shapeValue.Is3D);
return shapeValue.ToString("R");
}
public static string Figure3D()
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (!shapeValue.Is3D);
return shapeValue.ToString("R");
}
The only difference between them is the while-condition. How can I merge these two into one function? Passing parameter values is probably necessary & acceptable, but I do like to keep it short. Any ideas?
how about
public static string Figure(Predicate<dynamic> p)
{
dynamic shapeValue;
do
{
shapeValue = Presentation.Present();
}
while (p(shapeValue));
return shapeValue.ToString("R");
}

Creating a custom property class for multiple re-use within a class

Suppose I have a C# class that has multiple properties that all look like this:
private bool _var1Dirty = true;
private Double? _var1;
public Double? Var1
{
get
{
if (_var1Dirty)
{
_var1 = Method_Var1();
_var1Dirty = false;
}
return _var1;
}
}
And the only differences between each of these properties would be:
The type of return var (in this case Double?, but could just as easily be int, string, etc)
The method call - Method_Var1() (Each property would have a different one)
Is there any way I could write this as a custom class?
Something along the lines of:
public class Prop
{
public delegate T Func();
private bool _dirty = true;
private T _val;
public T Val
{
get
{
if (_dirty)
{
_val = Func;
_dirty = false;
}
return _val;
}
}
}
And then I could pass into it the:
Return type T
Method Func
(PS - I know this won't compile / is dead wrong, but I wanted to give an idea of what I'm looking for)
Any help / guidance would be really appreciated.
Thanks!!!
You're close. You can do something along the lines of this:
public class Dirty<T>
{
public Dirty(Func<T> valueFactory)
{
this.valueFactory = valueFactory;
dirty = true;
}
private Func<T> valueFactory;
private bool dirty;
private T value;
public T Value
{
get
{
if (dirty)
{
value = valueFactory();
dirty = false;
}
return value;
}
}
}
And you consume it like this:
Dirty<double?> dirtyDouble = new Dirty<double?>(() => SomethingThatReturnsADouble());
double? value = dirtyDouble.Value;
I'm not sure what the dirty checking actually does, but if you need someone more complicated than a bool you can always turn it into some Func<T> the checks for dirtiness.
Edit:
Given #mikez comment and your answer, you can save yourself the creation of the Dirty<T> class by using the built in Lazy<T>, which also guarantess thread safety:
public class F
{
private Lazy<double?> lazyDouble = new Lazy<double?>(() =>
MethodThatReturnsNullableDouble(), true);
public double? Value
{
get
{
return lazyDouble.Value;
}
}
}

Add methods to Func

I have a list of Func and I want to add elements.
If I add them on Start like below, no problem:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>();
void Start()
{
conditions.Add(Iamdead);
conditions.Add(Iamalive);
}
bool Iamdead()
{
...
return ...;
}
bool Iamalive()
{
...
return ...;
}
But I want to define the list without Start so that I have a clean list of methods that I can see as elements in a row. I have tried the classic format:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
bool Iamdead()
{
...
return ...;
}
,
bool Iamalive()
{
...
return ...;
}
};
This gave me parsing error
I tried like that:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
Iamdead,Iamalive
};
static bool Iamdead()
{
...
return ...;
}
static bool Iamalive()
{
...
return ...;
}
This worked only if the methods are static but I do not want them to be static. Without static, it doesn't work. It seems I couldn't understand the data structure here. Can anyone tell me the correct way of defining Func in a list?
Thanks
I strongly suspect the problem is that you're trying to access this (implicitly) within a field initializer. You're not allowed to do that. Just move the initialization into a constructor:
// You don't really use public fields, do you?
private readonly List<Func<bool>> conditions;
public MyClass()
{
conditions = new List<Func<bool>> { Method1, Method2 };
}
private bool Method1() { ... }
private bool Method2() { ... }
(I'm assuming you actually want your conditions to depend on state within the instance. If they don't, you don't need this. If the methods aren't used other than for these conditions, and they're short enough, you might want to use lambda expressions instead.)
Like so:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
() => false,
() => true,
};
You can just use lambdas:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
() =>
{
return false;
}
,
() =>
{
return true;
}
};

Categories

Resources