For example the main method I want to call is this:
public static void MasterMethod(string Input){
/*Do some big operation*/
}
Usually, I would do something like this this:
public static void StringSelection(int a)
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
}
MasterMethod(StringSelection(2));
But I want to do something like this:
MasterMethod( a = 2
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
});
Where 2 is somehow passed into the operation as an input.
Is this possible? Does this have a name?
EDIT:: Please note, the MasterMethod is an API call. I cannot change the parameters for it. I accidentally made a typo on this.
You can do this via delegates in C#:
public static string MasterMethod(int param, Func<int,string> function)
{
return function(param);
}
// Call via:
string result = MasterMethod(2, a =>
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
});
You can do this with anon delegates:
delegate string CreateString();
public static void MasterMethod(CreateString fn)
{
string something = fn();
/*Do some big operation*/
}
public static void StringSelection(int a)
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
}
MasterMethod(delegate() { return StringSelection(2); });
anonymous methods
Yes, use a delegate. Which include Lambda Expressions and anonymous methods
I think you're looking for a delegate.
Related
Let's imagine that I have the following overloaded function:
void DoSomething(int x) { ... }
void DoSomething(float x) { ... }
void DoSomething(decimal x) { ... }
In the following method, I need to call the correct overload. This is how a simple implementation would look like:
void HaveToDoSomething(object data)
{
if (data is int) DoSomething((int)data);
else if (data is float) DoSomething((float)data);
else if (data is decimal) DoSomething((decimal)data);
}
This is tedious when there are ~20 types to check. Is there a better way of doing all this casting automatically?
Something I forgot to mention: DoSomething wouldn't work with generics, as each type needs to be handled differently, and I only know the type at runtime.
One possible approach would be to use dynamic:
void HaveToDoSomething(dynamic data)
{
DoSomething(data);
}
You can use Reflection but it can have a performance impact:
public class Example
{
void DoSomething(int i)
{
}
void DoSomething(float i)
{
}
}
public static class ExampleExtensions
{
public static void DoSomethingGeneric(this Example example, object objectParam)
{
var t = objectParam.GetType();
var methods = typeof(example).GetMethods().Where(_ => _.Name == "DoSomething");
var methodInfo = methods.Single(_ => _.GetParameters().First().ParameterType == t);
methodInfo.Invoke(example, new[] { objectParam });
}
}
Any suggestion how to make the below query more "readable"?
var result = result
.OrderBy(a =>
(conditionA) ?
valueA :
(conditionB ? valueB :
(conditionC ?
(conditionD ?
valueC : valueD) :
valueE)));
Its difficult to read with the long code of condition and value.
There are several ways of improving the readability of your code.
Indentation
One way is to indent the code in a slightly different way, but this only helps readability a little:
var result = result.OrderBy(a =>
conditionA ? valueA :
conditionB ? valueB :
conditionC ? conditionD ? valueC :
valueD :
valueE);
if, else
You could also turn those ternary operators into a more readable chain of if, else.
var result = Result.OrderBy(a => {
if (conditionA)
{
return valueA;
}
else if (conditionB)
{
return valueB;
}
else if (conditionC)
{
if (conditionD)
{
return valueC;
}
else
{
return valueD;
}
}
else
{
return valueE;
}
});
IComparer<>
One option would be to write your own implementation of IComparer<> and pass it to the OrderBy method. I don't know what type your object is or what type the keys are in your code, so I'm going to assume string keys.
public class MyClassComparer : IComparer<MyClass>
{
public int Compare(MyClass x, MyClass y)
{
string xKey = getKey(x);
string yKey = getKey(y);
return string.Compare(xKey, yKey);
}
private string getKey(MyClass item)
{
if (item.conditionA)
{
return item.valueA;
}
else if (item.conditionB)
{
return item.valueB;
}
else if (item.conditionC)
{
if (item.conditionD)
{
return item.valueC;
}
else
{
return item.valueD;
}
}
else
{
return item.valueE;
}
}
}
Extension method
A final option would be to move your code to an extension method:
public static class MyClassExtensions
{
public static string GetSortingKey(this MyClass item)
{
if (item.conditionA)
{
return item.valueA;
}
else if (item.conditionB)
{
return item.valueB;
}
else if (item.conditionC)
{
if (item.conditionD)
{
return item.valueC;
}
else
{
return item.valueD;
}
}
else
{
return item.valueE;
}
}
}
Using the last option, your call to OrderBy is simply:
result.OrderBy(a => a.GetSortingKey())
I have a lot of methods that are doing the exact same if checks. Is it possible to wrap these methods in some way so I don't have to repeat the check?
For example, I have lots of methods like these:
public void Method1(int i)
{
if (isThisTrue())
{
SomeMethod(i, 2, 3); // returns void
}
else
{
SomeMethod2(i, "TestString"); // returns void
}
}
public string Method2()
{
if (isThisTrue())
{
return OtherMethod(1, true);
}
else
{
return OtherMethod2(1, "RandomString", 2);
}
}
Because the body of the if else else clauses is different, a simple cache aspect does not work. I thought about creating an Action or a Func for this, but the methods (SomeMethod, SomeMethod2, OtherMethod, and OtherMethod2) signatures are different. Having a whole bunch of them for every possible method signatures doesn't seem sustainable.
Is there a simple way to abstract this out?
The fact that you want to return void in some instances makes it a bit awkward as void doesn't work with generics. You could do something like this though:
public void Method1(int i)
{
this.PredicateMethod(
NullFunc(() => SomeMethod(i, 1, 2)),
NullFunc(() => SomeMethod2(1, "RandomString")));
}
public string Method2()
{
return this.PredicateMethod(
() => OtherMethod(1, true),
() => OtherMethod2(1, "RandomString", 2));
}
private Func<object> NullFunc(Action a)
{
return new Func<object>(() =>
{
a();
return null;
});
}
private T PredicateMethod<T>(Func<T> trueMethod, Func<T> falseMethod)
{
return IsThisTrue() ? trueMethod() : falseMethod();
}
Or implement a base class to capture the logic:
public abstract class PredicateBase
{
private readonly Func<bool> _predicate;
protected PredicateBase(Func<bool> predicate)
{
_predicate = predicate;
}
protected T PredicateMethod<T>(Func<T> trueMethod, Func<T> falseMethod)
{
return _predicate() ? trueMethod() : falseMethod();
}
protected void PredicateMethod(Action trueMethod, Action falseMethod)
{
if (_predicate())
trueMethod();
else
falseMethod();
}
}
You can use optional parameters is much better than spaghetti code!
public object Method(int i = -999)
{
if(i != -999){//Method #1
if (isThisTrue())
{
SomeMethod(i, 2, 3); // returns void
}
else
{
SomeMethod2(i, "TestString"); // returns void
}
}else{//Method #2
if (isThisTrue())
{
return OtherMethod(1, true);
}
else
{
return OtherMethod2(1, "RandomString", 2);
}
}
}
How can I define a function that expects another function that returns a bool in c#?
To clarify, this is what I'd like to do using C++:
void Execute(boost::function<int(void)> fctn)
{
if(fctn() != 0)
{
show_error();
}
}
int doSomething(int);
int doSomethingElse(int, string);
int main(int argc, char *argv[])
{
Execute(boost::bind(&doSomething, 12));
Execute(boost::bind(&doSomethingElse, 12, "Hello"));
}
In my example above the Execute function in combination is with the bind gets the expected result.
Background:
I've got a bunch of functions, each returning a int but with different parameter count that are surrounded by the same error checking code. A huge code duplication I want to avoid...
You can probably achieve what you want by using Func. For example
void Execute(Func<bool> myFunc)
{
if(myFunc() == false)
{
// Show error
}
}
You can then define your Func either as a method, or a lambda:
// Define a method
private bool MethodFunc() {}
// Pass in the method
Execute(MethodFunc)
// Pass in the Lambda
Execute(() => { return true; });
You don't nececssairly need to pass the parameters in as you can now access them from the caller's scope:
Execute(() => { return myBool; });
Execute(() => { return String.IsNullOrEmpty(myStr); });
With my solution, you can perform any function, any input parameter, with any return, this is a very generic implementation
Example:
public T YourMethod<T>(Func<T> functionParam)
{
return functionParam.Invoke();
}
public bool YourFunction(string foo, string bar, int intTest)
{
return true;
}
Call like This specifying the return :
YourMethod<bool>(() => YourFunction("bar", "foo", 1));
Or like this:
YourMethod(() => YourFunction("bar", "foo", 1));
without argument do this
void Execute(Func<bool> fctn)
{
if(fctn() )
{
show_error();
}
}
with arguments you can do something like this:
void Execute<T>(Func<T[],bool> fctn)
{
var v = new T[4];
if(fctn(v) )
{
show_error();
}
}
I have the following code, I want to refactor the duplication out of:
public bool HasBia
{
get
{
if (IsC2User())
{
return true;
}
if(_hasBia == null)
{
_hasBia = _excludes.HasBia;
}
return _hasBia.Value;
}
}
public bool HasTeachAndTest
{
get
{
if (IsC2User())
{
return true;
}
if(_hasTeachAndTest == null)
{
_hasTeachAndTest = _excludes.HasTeachAndTest;
}
return _hasTeachAndTest.Value;
}
}
The bit I am having trouble with is that, _excludes.HasBia and _excludes.HasTeachAndTest are dynamic expressions or dynamic properties that are resolved by TryGetMember of a class that inherits from DynamicObject.
I think I want to do something like this:
public bool HasPermission(bool? value, DynamicExpression expression)
{
if (IsC2User())
{
return true;
}
}
Then I can call it like this:
return HasPermission(_hasBia, _excludes.HasTeachAndTest);
But I am unsure how to invoke the expression when it is passed into the HasPermission method.
Anybody got any ideas?
Perhaps this would work.
public bool HasPermission(ref bool? field, bool defaultValue)
{
if (IsC2User())
{
return true;
}
if (field == null) //lazy loading a bool? overkill? :)
{
field = defaultValue;
}
return field;
}
//usage
public bool HasBia
{
get
{
return HasPermission(ref _hasBia, _excludes.HasBia);
}
}
Or if there are side effects of retrieving the default value
public bool HasPermission(ref bool? field, Func<bool> getDefaultValue)
{
if (IsC2User())
{
return true;
}
if (field == null)
{
field = getDefaultValue();
}
return field;
}
//usage
public bool HasTeachAndTest
{
get
{
return HasPermission(ref _hasTeachAndTest, () => _excludes.HasTeachAndTest);
}
}
I don't think it makes any sense to remove this sort of duplication, consider the additional complexity introduced by any of the possible solutions vs. the simplicity of repeating a pattern at two places.
Perhaps what you are really missing is a concept in your problem domain that you are trying to come by with duplication in your solution domain. Jeff M's solution is fine in regards to a technical implementation, but I'd not use it in this simple case.