C# Programming (Tips)
How to do Functional programming style with "C#"?
You can use different ways to perform If you need to perform serious domain rules to evaluate.
In the method, you can use If/switch statements to evaluate the rules one by one and return the result in an imperative way. However, this doesn't give you good composability. We can do better than this.
Each rule could be defined as Func<T,U> and combined in Array and executed. All functions over the array pass data for each element of the array (which is functions) to evaluate them. Array here is the composition container and All execute all elements over the array. Each element of the array has the same type T and same return type U so this method can work.
Example;
private readonly Func<string,bool> rule1 = x => x.length == 10;
private readonly Func<string,bool> rule2 = x => new Regex("[a-zA-Z]").IsMatch(x);
private readonly Func<string,bool> rule3 = x => {
return x.Contains("Hello");
};
public bool ValdateTheRules(String data){
new [] {
rule1,
rule2,
rule3
}.All( fnc => fnc(data) );
};
Record Type
Sometimes you might have a set of values that you want to create a copy of it with changing some subset of the data. The record type is useful in this type of situation and useful if you don't want to pass the reference of the object around because of shared data state might cause a problem ( like parallelism)
public record Person {
public String Name {get; set;}
public int Age { get; set; }
}
var p1 = new Person { Name: "Ben", Age: 47 };
var p2 = p1 with { Age: 35 };
Monads Simplified
The Identity is like a box (wrapped T in Identity Type) of any type T. Bind takes function and Identity for T, extracts T and executes the function on T, and put the result into the Identity. At the end of the Binds chain, we need a mechanism to extract the result from the Identity box to release the final result to the other Identities. Eventually, this way we can combine data and logic in Monads and chain them and compose multiple monads to create higher-order functions.