Simple If and Else If Using Functions - c#

Given this example snippet:
if(test == 5) {
var = 5;
var2 = 6;
}
else if(test == 6){
var = 30;
var2 = 25;
}
//...ect
How can I clean this up into a function? I thought of doing this:
void doStuff(int condition, int v1, int v2){
if(test == condition){
var = v1;
var2 = v2;
}
}
but then I would have to implement it like this:
doStuff(5,5,6);
doStuff(6,30,25);
//...ect
This would go through each function and check each if statement even if the first was evaluated to be true. This would not have the if, else if, else function unless I did something like this:
//Assuming doStuff returns a bool
if(doStuff(5,5,6)
else if(doStuff(6,30,25))
//...ect
Is there a better way to put functions inside conditional if / else if statements?

The switch approach is probably the best, but if the number of cases is huge, you can consider doing something funny like...
private static readonly Dictionary<int, int[]> _dic = new...
private void Foo()
{
var test = ...
var vals = this._dic[test];
a = vals[0];
b = vals[1];
...
}
And if not all variables are of type int, you can either use Tuple or your own structure to hold the information (+1 for naming values)
Edit: regarding your updated question about "better way to use methods in if-else":
doStuff(5,5,6) || doStuff(6,30,25) || ...
Will evaluate doStuff's from left to right until one returns true.

var conditionsMap = new Dictionary<int, Tuple<int, int>>();
conditionsMap.Add(5, new Tuple<int, int>(5, 6));
conditionsMap.Add(6, new Tuple<int, int>(30, 25));
foreach (var entry in conditionsMap)
{
var key = entry.Key;
var var1 = entry.Value.Item1;
var var2 = entry.Value.Item2;
Console.WriteLine("{0}\n{1}\n{3}", key, var1, var2);
}

In these situations, I tend to use an enum with custom attributes to define the different conditions. To me, that keeps it concise which aids in maintenance and also helps restrict the possible inputs to a predefined set.
Here's a full code sample (it can be pasted into LINQPad to test):
public class ValuesAttribute : Attribute
{
public int V1 { get; private set; }
public int V2 { get; private set; }
public ValuesAttribute(int v1, int v2)
{
V1 = v1;
V2 = v2;
}
}
public enum ValuesCase
{
[Values(5, 6)]
Five,
[Values(30, 25)]
Six
}
public void DoStuff(ValuesCase valuesCase)
{
// There are several ways to get an attribute value of an enum, but I like this one
ValuesAttribute values = valuesCase
.GetType()
.GetTypeInfo()
.GetDeclaredField(valuesCase.ToString())
.GetCustomAttribute<ValuesAttribute>();
if(values != null)
{
// Assign your variables or do whatever else you want here
Console.WriteLine(string.Join(", ", valuesCase.ToString(), values.V1, values.V2));
}
}
void Main()
{
DoStuff(ValuesCase.Five);
DoStuff(ValuesCase.Six);
}

Related

C# Generic variable changes if another same type generic changes

I've this class:
public class Pair<T, V>
{
public T A = default;
public V B = default;
public Pair()
{
A = default;
B = default;
}
public Pair(T a, V b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
Pair<T, V> other = obj as Pair<T, V>;
return A.Equals(other.A) && B.Equals(other.B);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return "Pair: (" + A.ToString() + " , " + B.ToString() + ")";
}
}
And I have a class with two Pair variables:
public class FakeClass<T>
{
public T LastValue { get; protected set; } = default;
public T CurrentValue = default;
public void Execute()
{
LastValue = CurrentValue
}
}
public class FakeClassWithPair : FakeClass<Pair<int, int>> { }
Now if I execute this code:
FakeClassWithPair fake = new FakeClassWithPair();
fake.CurrentValue.A = 2;
fake.CurrentValue.B = 5;
fake.Execute();
fake.CurrentValue.A = 32;
fake.CurrentValue.B = 53;
In debugging Current Value and Last Value have the same value "32" and "53".
How can I avoid this?
Classes are reference types, so when you set LastValue = CurrentValue, that means both LastValue and CurrentValue refer to the same object.
If you want Value semantics you should declare your Pair as a struct. This means that an assignment does a copy of the value. Except ofc there already are a built in type for this: ValueTuple, with some special syntax that lets you declare types like (int A, int B). There is also a regular Tuple<T1, T2> if you do want a reference type.
Also note that I see no way for your example to run, fake.CurrentValue should be initialized to null and crash when accessed. Using a value type would also solve this, since they cannot be null.
So just change your example to FakeClassWithPair:FakeClass<(int A, int B)> and everything should work as you expect it to.
Definitely do not roll your own class for a pair if you want value semantics. Use the built-in value tuple, defined as (T a, V b).
Also if your content of FakeClass is cloneable then you should take advantage of that (for example arrays are cloneable). So the assignment in Execute() would check if the current value implements ICloneable and proceeds accordingly.
See this example code with output. The first example with fk variable is defined by FakeClass<(int,int)> and the second example with fa variable is defined by FakeClass<int[]>. Some fun code is added to display arrays as list of vales in ToString() in order to mimic the behavior of tuples with arrays.
public class FakeClass<T>
{
public T LastValue { get; protected set; } = default(T);
public T CurrentValue = default(T);
public void Execute()
{
if (CurrentValue is ICloneable cloneable)
{
LastValue = (T)cloneable.Clone();
}
else
{
LastValue = CurrentValue;
}
}
public override string ToString()
{
if (typeof(T).IsArray)
{
object[] last, current;
Array cv = CurrentValue as Array;
if (cv != null)
{
current = new object[cv.Length];
cv.CopyTo(current, 0);
}
else
{
current = new object[0];
}
Array lv = LastValue as Array;
if (lv != null)
{
last = new object[lv.Length];
lv.CopyTo(last, 0);
}
else
{
last = new object[0];
}
return $"Current=[{string.Join(",",current)}], Last=[{string.Join(",",last)}]";
}
return $"Current={CurrentValue}, Last={LastValue}";
}
}
class Program
{
static void Main(string[] args)
{
var fk = new FakeClass<(int a, int b)>();
fk.CurrentValue = (1, 2);
Console.WriteLine(fk);
// Current=(1, 2), Last=(0, 0)
fk.Execute();
fk.CurrentValue = (3, 4);
Console.WriteLine(fk);
// Current=(3, 4), Last=(1, 2)
var fa = new FakeClass<int[]>();
fa.CurrentValue = new int[] { 1, 2 };
Console.WriteLine(fa);
//Current=[1,2], Last=[]
fa.Execute();
fa.CurrentValue = new int[] { 3, 4 };
Console.WriteLine(fa);
//Current=[3,4], Last=[1,2]
}
}

Get key in dictionary with optional tuple parameter

I have a dictionary that looks like this Dictionary<Tuple<int, int, bool>, string>
Let's say I have an entry like (1, 2, true) = "Word"
I want to be able to index the dictionary by only doing (1, null, true) and I want it to return the entry I mentioned before since the first and third values in the tuple are the same (ignoring the second since it's null)
Is there a way to do this? If not what is a suggestion for a new structure that would accomplish this? Thanks
I'd suggest you to create a struct to use instead of your Tuple, overriding GethashCode() (implement Equals too, to be consistent) :
public struct MyStruct
{
public int? FirstNumber { get; set; }
public int? SecondNumber { get; set; }
public bool TheBoolean { get; set; }
public override bool Equals(object obj)
{
return this.Equals((MyStruct)obj);
}
public bool Equals(MyStruct obj)
{
return (!obj.FirstNumber.HasValue || !this.FirstNumber.HasValue ||
obj.FirstNumber.Value == this.FirstNumber.Value)
&& (!obj.SecondNumber.HasValue || !this.SecondNumber.HasValue ||
obj.SecondNumber.Value == this.SecondNumber.Value)
&& obj.TheBoolean == this.TheBoolean;
}
public override int GetHashCode()
{
return (!this.FirstNumber.HasValue ? 0 : this.FirstNumber.GetHashCode())
^ (!this.SecondNumber.HasValue ? 0 : this.SecondNumber.GetHashCode())
^ this.TheBoolean.GetHashCode();
}
}
public static void Test()
{
var obj1 = new MyStruct
{
FirstNumber = 1,
SecondNumber = 2,
TheBoolean = true
};
var obj2 = new MyStruct
{
FirstNumber = 1,
SecondNumber = null,
TheBoolean = true
};
var dico = new Dictionary<MyStruct, string>
{
{ obj1, "Word" }
};
var result = dico[obj2];
Console.WriteLine(result);
}
The idea behind a Dictionary<TKey, TValue> is that you really need to have identical match between your TKey, TValuepairs. So, according to your structure, you could try something like this:
Dictionary<tuple<int, bool>, string>
where, in the dictionary creation step, you take in two ints, and combine them into a new, unitque value to add to your dictionary. Here is an example:
public static void AddToDictionary(
this Dictionary<Tuple<int, bool>, string> dictionary,
Tuple<int, int, bool> oldKey,
string value)
{
var key = new Tuple<int, bool>(oldKey.Item1 + oldKey.Item2, oldKey.Item3);
dictionary[key] = value;
}
Bear in mind that the key values must be UNIQUE. Otherwise, you will overwrite older entries.
Another structure that you can have is a Dictionary of Dictionaries. Since you are only interested in the first int, and since the second int might be null, you can have this:
Dictionary<int, Dictionary<Tuple<int?, bool>, string>>
This way, you can get something like this:
var keyTuple = new Tuple<int, int?, bool>(1, null, true);
myDictionary[keyTuple .Item1][new Tuple<int?, bool>(keyTuple.Item2, keyTuple.Item3)]
= "string value";
But, again, it starts to get verbose... a lot.

Replicating dynamic multi-dimensional array creation of PHP

So, I am converting a project from PHP to C#. Got a Generic List of data as a result of a query
//C# code
public class TermsCommodityModel
{
public int terms_id { get; set; }
public int commodity_id { get; set; }
public int custom { get; set; }
public int calculated { get; set; }
public string name { get; set; }
public string formula { get; set; }
public int division_id { get; set; }
}
I was able to populate it into termsTable which is a List<TermsCommodityModel>. Then the PHP code started looping the termsTable.( C# and PHP codes use same variable for easy conversion). The first line completely altered my datastructure
//PHP code
if (!isset($termsTable[$name]))
$termsTable[$name] = array();
I thought, weird but doable. Then the second condition created another child array and it went on. Now the PHP code looks so,
//PHP Code
if (!isset($termsTable[$name][$t->commodity_id]))
$termsTable[$name][$t->commodity_id] = array();
//.Omitted for brevity
//....
$year = date("Y") + 5;
for ($y = 2008; $y<= $year; $y++) {
$termsTable[$name][$t->commodity_id][$y] = array();
for ($i=1; $i<=12; $i++)
$termsTable[$name][$t->commodity_id][$y][$i] = 0;
}
This is the final data-structure
//PHP Code
$termsTable[$name]
$termsTable[$name][$t->commodity_id]
$termsTable[$name][$t->commodity_id][$y]
$termsTable[$name][$t->commodity_id][$y][$i]
This essentially created an array of an array of an array of an array of an object dynamically. The thing is PHP is a dynamically typed language. It doesn't need to specify a type
Which data-structure in C# could possibly do this? Cant use a tuple as they are hierarchical, right?
Which way to approach this? Any pointers will be extremely helpful as this is kinda important.
I'm not sure how TermsCommodityModel is related to php code, because it's not shown anywhere there as far as I can tell. Anyway, you can achieve syntax similar to php by (ab)using dynamic and DynamicObject. First create class like this:
public class DynamicDictionary : DynamicObject {
private readonly Dictionary<object, object> _dictionary;
public DynamicDictionary() {
_dictionary = new Dictionary<object, object>();
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
// this will be called when you do myDict[index] (but not myDict[index] = something)
if (indexes.Length != 1)
throw new Exception("Only 1-dimensional indexer is supported");
var index = indexes[0];
// if our internal dictionary does not contain this key
// - add new DynamicDictionary for that key and return that
if (_dictionary.ContainsKey(index)) {
_dictionary.Add(index, new DynamicDictionary());
}
result = _dictionary[index];
return true;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) {
// this will be called when you do myDict[index] = value
if (indexes.Length != 1)
throw new Exception("Only 1-dimensional indexer is supported");
var index = indexes[0];
// just set value
_dictionary[index] = value;
return true;
}
}
And use it like this:
dynamic termsTable = new DynamicDictionary();
var name = "name";
int commodityId = 123;
var year = DateTime.Now.Year + 5;
for (int y = 2008; y <= year; y++) {
for (int i = 1; i < 12; i++) {
// that's fine
termsTable[name][commodityId][y][i] = 0;
}
}
// let's see what we've got:
for (int y = 2008; y <= year; y++) {
for (int i = 1; i < 12; i++) {
// that's fine
Console.WriteLine(termsTable[name][commodityId][y][i]);
}
}
To mirror your php code even more, change TryGetIndex like this:
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
// this will be called when you do myDict[index] (but not myDict[index] = something)
if (indexes.Length != 1)
throw new Exception("Only 1-dimensional indexer is supported");
var index = indexes[0];
// if our internal dictionary does not contain this key
// return null
if (!_dictionary.ContainsKey(index)) {
result = null;
}
else {
result = _dictionary[index];
}
return true;
}
Then you need to check if such key already exists (which is a bit better to my mind):
dynamic termsTable = new DynamicDictionary();
var name = "name";
int commodityId = 123;
var year = DateTime.Now.Year + 5;
// need to check if such key exists
// like isset in php
if (termsTable[name] == null)
termsTable[name] = new DynamicDictionary();
if (termsTable[name][commodityId] == null)
termsTable[name][commodityId] = new DynamicDictionary();
for (int y = 2008; y <= year; y++) {
if (termsTable[name][commodityId][y] == null)
termsTable[name][commodityId][y] = new DynamicDictionary();
for (int i = 1; i < 12; i++) {
// that's fine
termsTable[name][commodityId][y][i] = 0;
}
}
Of course type safery is thrown out of the window by doing that, but if you are fine with that - why not.
Although the code in my first answer reproduces the original logic written in PHP, it lacks some very important qualities. It is not self-explanatory, and it is hard to read.
Specifically, things like Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<int, int>>>> is a huge anti-pattern. No one knows what is expected to be in the keys and in the values of this monster data structure. It is too error-prone.
A much better way to factor the code would be as follows:
public class TermsTable
{
private readonly Dictionary<string, IndexByCommodityId> _index;
public TermsTable(IEnumerable<TermsCommodityModel> list)
{
_index = list
.GroupBy(tcm => tcm.name)
.ToDictionary(
tcmGroup => tcmGroup.Key,
tcmGroup => new IndexByCommodityId(tcmGroup));
}
public IndexByCommodityId this[string name] => _index[name];
}
public class IndexByCommodityId
{
private readonly Dictionary<int, IndexByYear> _index;
public IndexByCommodityId(IEnumerable<TermsCommodityModel> list)
{
_index = list.ToDictionary(
keySelector: tcm => tcm.commodity_id,
elementSelector: tcm => new IndexByYear());
}
public IndexByYear this[int commodityId] => _index[commodityId];
}
public class IndexByYear
{
private static readonly int _nowYear = DateTime.Now.Year;
private readonly Dictionary<int, IndexByMonth> _index;
public IndexByYear()
{
_index = Enumerable
.Range(2008, _nowYear - 2008 + 1)
.ToDictionary(
keySelector: year => year,
elementSelector: year => new IndexByMonth());
}
public IndexByMonth this[int year] => _index[year];
}
public class IndexByMonth
{
private readonly Dictionary<int, int> _index;
public IndexByMonth()
{
_index = Enumerable.Range(1, 12).ToDictionary(month => month, month => 0);
}
public int this[int month]
{
get => _index[month];
set => _index[month] = value;
}
}
The code that uses the new data structure would look like this:
// a flat list of TermsCommodityModel, filled with data elsewhere
List<TermsCommodityModel> list = new List<TermsCommodityModel>();
// create our hierarchical index from the above list
TermsTable aBetterTermsTable = new TermsTable(list);
string name = "ABC";
int commodityId = 12345;
int year = 2010;
int month = 10;
int value = aBetterTermsTable[name][commodityId][year][month];
Yes, it is much more code to write, but its worth it. It is easier to read, and less error prone. For instance, one of the benefits is IntelliSense:
I have little knowledge in PHP, but it looks like I can follow. The code you demonstrate in your question is based on associative arrays. In .NET, associative arrays are usually implemented through Dictionary<TKey, TValue> data structure.
You start with a flat List<TermsCommodityModel>, and then you can build hierarchical dictionary-based structures as follows:
// a flat list of TermsCommodityModel, filled with data elsewhere
List<TermsCommodityModel> list = new List<TermsCommodityModel>();
Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<int, int>>>> termsTable = list
.GroupBy(tcm => tcm.name)
.ToDictionary(
tcmGroup => tcmGroup.Key,
tcmGroup => tcmGroup.ToDictionary(
tcm => tcm.commodity_id,
tcm => CreateYearMonthTable()));
and one more helper function:
static Dictionary<int, Dictionary<int, int>> CreateYearMonthTable()
{
var year = DateTime.Now.Year + 5;
return Enumerable
.Range(2008, year - 2008 + 1)
.ToDictionary(
y => y,
y => Enumerable.Range(1, 12).ToDictionary(i => i, i => 0));
}
the following is an example of how you access the leaf values in this data structure:
string name = "ABC";
int commodityId = 12345;
int year = 2010;
int month = 10;
int value = termsTable[name][commodityId][year][month];
EDIT
A better approach to solve the problem is in my second answer:
https://stackoverflow.com/a/47593724/4544845

Can we get access to the F# copy and update feature from c#?

For example in F# we can define
type MyRecord = {
X: int;
Y: int;
Z: int
}
let myRecord1 = { X = 1; Y = 2; Z = 3; }
and to update it I can do
let myRecord2 = { myRecord1 with Y = 100; Z = 2 }
That's brilliant and the fact that records automatically implement IStructuralEquality with no extra effort makes me wish for this in C#. However Perhaps I can define my records in F# but still be able to perform some updates in C#. I imagine an API like
MyRecord myRecord2 = myRecord
.CopyAndUpdate(p=>p.Y, 10)
.CopyAndUpdate(p=>p.Z, 2)
Is there a way, and I don't mind dirty hacks, to implement CopyAndUpdate as above? The C# signiture for CopyAndUpdate would be
T CopyAndUpdate<T,P>
( this T
, Expression<Func<T,P>> selector
, P value
)
It can be done, but doing that properly is going to be quite hard (and it definitely won't fit in my answer). The following simple implementation assumes that your object has only read-write properties and parameter-less constructor:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
This slightly defeats the point, because you would probably want to use this on immutable types - but then you always have to call the constructor with all the arguments and it is not clear how to link the constructor parameters (when you create an instance) with the properties that you can read.
The With method creates a new instance, copies all property values and then sets the one that you want to change (using the PropertyInfo extracted from the expression tree - without any checking!)
public static T With<T, P>(this T self, Expression<Func<T, P>> selector, P newValue)
{
var me = (MemberExpression)selector.Body;
var changedProp = (System.Reflection.PropertyInfo)me.Member;
var clone = Activator.CreateInstance<T>();
foreach (var prop in typeof(T).GetProperties())
prop.SetValue(clone, prop.GetValue(self));
changedProp.SetValue(clone, newValue);
return clone;
}
The following demo behaves as expected, but as I said, it has lots of limitations:
var person = new Person() { Name = "Tomas", Age = 1 };
var newPerson = person.With(p => p.Age, 20);
In general, I think using a universal reflection-based method like With here might not be such a good idea, unless you have lots of time to implement it properly. It might be easier to just implement one With method for every type that you use which takes optional parameters and sets their values to a cloned value (created by hand) if the value is not null. The signature would be something like:
public Person With(string name=null, int? age=null) { ... }
You could achieve something similar using optional arguments:
class MyRecord {
public readonly int X;
public readonly int Y;
public readonly int Z;
public MyRecord(int x, int y, int z) {
X = x; Y = y; Z = z;
}
public MyRecord(MyRecord prototype, int? x = null, int? y = null, int? z = null)
: this(x ?? prototype.X, y ?? prototype.Y, z ?? prototype.Z) { }
}
var rec1 = new MyRecord(1, 2, 3);
var rec2 = new MyRecord(rec1, y: 100, z: 2);
This is actually pretty close to the code that F# generates for records.
In case anyone else is stumbling upon this, I recently needed to do the same thing and was able to take #Tomas Petricek's answer and expand it to work with immutable records:
public static T With<T, P>(this T self, Expression<Func<T, P>> selector, P newValue)
{
var me = (MemberExpression)selector.Body;
var changedProp = (System.Reflection.PropertyInfo)me.Member;
var constructor = typeof(T).GetConstructors()[0];
var parameters = constructor.GetParameters().Select(p => p.Name);
var properties = typeof(T).GetProperties();
var args = parameters
.Select(p => properties.FirstOrDefault(prop => String.Equals(prop.Name,p, StringComparison.CurrentCultureIgnoreCase)))
.Select(prop => prop == changedProp ? newValue : prop.GetValue(self))
.ToArray();
var clone = (T) constructor.Invoke(args);
return clone;
}
Usage
// F#
type Person =
{
Name : string
Age : int
}
// C#
var personRecord = new Person("John",1);
var newPerson = personRecord.With(p => p.Age, 20);

Problem in implementing my own switch class

I am trying to implement a custom switch case just for fun..
The approach is that I have created a class that inherits a dictionary object
public class MySwitch<T> : Dictionary<string, Func<T>>
{
public T Execute(string key)
{
if (this.ContainsKey(key)) return this[key]();
else return default(T);
}
}
And I am using as under
new MySwitch<int>
{
{ "case 1", ()=> MessageBox.Show("From1") },
{ "case 2..10", ()=>MessageBox.Show("From 2 to 10") },
}.Execute("case 2..10");
But if I specify "case 2" it gives a default value as the key is not in the dictionary.
The whole purpose of making "case 2..10 " is that if the user enters anything between case 2 to case 10, it will execute the same value.
Could anyone please help me in solving this?
Thanks
The string "case 2..10" is stored in the dictionary object and the only way contains key returns ture is if you supply exactly that string. meaning you would have to pass the exact string "case 2..10" to containskey to return true.
My adice would be to look at the specification pattern.
You can have each function have one or more specification attached to it and then execute the relevant function (or functions if you want).
In short:
public interface ISpecification<T>
{
bool IsSatisfiedBy(T item);
}
And a specific implementation:
public class IntegerRangeSpecification : ISpecification<int>
{
private readonly int min;
private readonly int max;
public IntegerRangeSpecification(int min, int max)
{
this.min = min;
this.max = max;
}
public bool IsSatisfiedBy(int item)
{
return (item >= min) && (item <= max);
}
}
Of course you would rather have RangeSpecification<T> : ISpecification<T> but that requires some more effort/design (such as where T : IComparable).
Anyway, I hope that gets you on the right track.
First you probably want to encapsulate a dictionary rather than extend a dictionary as I doubt you want all the methods of a dictionary in your switch class.
Second you will need to parse your case strings apart and add your own keys to the dictionary. The approach of using strings as keys strikes me as not the best of ideas. By using strings as your keys you are requiring that the keys match exactly. If you made your dictionary use integer keys and you changed how it was initialized. Keeping with the the spirit of your switch you could do something like this:
public class Switch<T>
{
private Dictionary<int, Func<T>> _switch = new Dictionary<int, Func<T>>();
private Func<T> _defaultFunc;
public Switch(Func<T> defaultFunc)
{
_defaultFunc = defaultFunc;
}
public void AddCase(Func<T> func, params int[] cases)
{
foreach (int caseID in cases)
{
_switch[caseID] = func;
}
}
public void AddCase( int beginRange, int endRange, Func<T> func)
{
for (int i = beginRange; i <= endRange; i++)
{
_switch[i] = func;
}
}
public T Execute(int caseID)
{
Func<T> func;
if(_switch.TryGetValue(caseID, out func)){
return func();
}else{
return _defaultFunc();
}
}
}
Which could be used like this:
Switch<int> mySwitch = new Switch<int>(() => {Console.WriteLine("Default"); return 0;});
mySwitch.AddCase(() => { Console.WriteLine("1"); return 1; }, 1);
mySwitch.AddCase(2, 10, () => { Console.WriteLine("2 through 10"); return 1; });
mySwitch.AddCase(() => { Console.WriteLine("11, 15, 17"); return 2; }, 11, 15, 17);
mySwitch.Execute(1);
mySwitch.Execute(2);
mySwitch.Execute(3);
mySwitch.Execute(4);
mySwitch.Execute(11);
mySwitch.Execute(12);
mySwitch.Execute(15);
There are a bunch of different ways you can accomplish what you want. Hope this helps some

Categories