Generically encapsulate action/function with class? - c#

I would like to provide encapsulation of actions/methods generically. I think this should be possible in C# but I'm not able to produce it so it compiles...
The following briefly demonstrates what I want. Is this possible somehow, perhaps by generalizing the class?
Required is:
I want to execute the function/action (see method type) and 'do something' when an error occurs
I want to return the value of the function if the method is a function (otherwise return void if possible)
I want to 'do something' if the return type of the function is a boolean and the value is false.
public class Encapsulator {
private Action _action;
private Func<T> _function;
private MethodType _type; //Action || Function
public Encapsulator(Action action) {
this._action = action;
this._type = MethodType.Action;
}
public Encapsulator(Func<T> func) { //This is not accepted
this._function = func;
this._type = MethodType.Function;
}
public void Execute() {
try {
this._action();
}
catch(Exception ex) {
//do something
throw;
}
}
public T Execute<T>() {
try {
var r = this._function();
if(typeof(r) == bool) {
if(!r)
//do something
}
return r;
} catch(Exception ex) {
//do something
throw;
}
}
}

Your second constructor won't compile because their are no generics applied to the type at the higher level:
public Encapsulator<T>
{
public Encapsulator(Func<T> func)
{
this._function = func;
this._type = MethodType.Function;
}
}
Instead of just introducing new things within the parameters of a method, essentially, we need to specify that those things are 'available' for utilisation in the definitions. So, for instance, if you were trying to add a specific generic method, you could apply it as you have done, but would instead need to do (something which you demonstrate with the Execute method):
public void MyGenericMethod<T>(Func<T> func)
{
}
Noting the first T, we're specifying the existence of T, as such.
There are possibly more issues at hand with your code here, but I believe, on first glance, this to be the crux of the problems you're having.
As for returning variable types, the best you might hope for is returning a plain old object. Or, making use of the dynamic type, however, I wouldn't have thought this would be the way to go and wouldn't recommend it; you can't flip return type from an actual type to a void, though.

New Approach: The action Encapsulator will now return a dummy result (always true).
public class Encapsulator
{
public static Encapsulator<bool> CreateEncapsulator(Action action)
{
return new Encapsulator<bool>(() =>
{
action();
return true;
});
}
public static Encapsulator<T> CreateEncapsulator<T>(Func<T> func)
{
return new Encapsulator<T>(func);
}
}
public class Encapsulator<T>
{
private Func<T> _function;
internal Encapsulator(Func<T> func)
{
this._function = func;
}
public T Execute()
{
try
{
object res = this._function();
Nullable<bool> bres = res as Nullable<bool>;
if (bres.HasValue)
{
if (!bres.Value)
Console.WriteLine("NOT TRUE!");
//do something
}
return (T)res;
}
catch (Exception ex)
{
//do something
throw;
}
}
}
Calling the code:
var withDummyReturn = Encapsulator.CreateEncapsulator(() => Console.WriteLine("Great"));
withDummyReturn.Execute();
var withReturn = Encapsulator.CreateEncapsulator<bool>(() => true);
bool res = withReturn.Execute();

Related

Use dynamic data type for TryParse

I have a process that allows users to upload data in Excel file and save to database once the data have gone series of validations . Once such validation is data type validation, to prevent them trying to put a string into integer field, for example. Here is an excerpt of the code. The caller (ValidateContentDataType) calls ValidateDataType() and passes property info and data in string to the callee to perform TryParse.
public void ValidateContentDataType()
{
//Do stuff
ValidateDataType(typeof(T).GetProperty("nameOfProperty"), data);
//Do stuff
}
private bool ValidateDataType(PropertyInfo propInfo, string dataElement)
{
if (propInfo is null) return true;
if (propInfo.PropertyType == typeof(decimal) || propInfo.PropertyType == typeof(decimal?))
{
return decimal.TryParse(dataElement, out decimal temp);
}
//Other ifs TryParse for different data type....
return true;
}
While this works, I don't like the series of ifs in ValidateDataType(). Instead of series of ifs for different data types, like this:
if (propInfo.PropertyType == typeof(decimal) || propInfo.PropertyType == typeof(decimal?))
{
return decimal.TryParse(dataElement, out decimal temp);
}
is it possible to have something like this:
return *propertyType*.TryParse(dataElement, out *propertyType *temp);
Stylistically, I'd probably write that as a switch statement:
switch (propInfo.PropertyType)
{
case typeof(decimal):
case typeof(decimal?):
return decimal.TryParse(dataElement, out decimal temp);
case typeof(int):
case typeof(int?):
return ...
}
I think that looks a lot better than multiple if statements. But I freely admit that it's a subjective opinion.
There might be a solution that involves creating a generic method that expects a type that implements the IParseable interface. Something like:
private bool ValidateDataType<T>(...) where T:IParseable
But I haven't completely worked it out. Might be that you'd have to call the method through reflection.
OK. IParsable gives me what I need. Creating a couple of extensions with the the type parameter T that implements IParsable. Then invoke the extensions so I can use the property types from reflection. Seems to be a lot of work for something seemingly trivia. Anyway, here is what I came up with:
internal class Program
{
static void Main(string[] args)
{
Type myClassType = typeof(MyClass);
PropertyInfo propInfo = myClassType.GetProperty("ForecastYear");
ValidateDataType(propInfo.PropertyType, "2023");
}
static void ValidateDataType(Type propertyType, string input)
{
MethodInfo method = typeof(TryParseExtensions).GetMethod(nameof(TryParseExtensions.TryParse));
MethodInfo generic = method.MakeGenericMethod(propertyType);
object[] args = { input, null };
var parseSuccessful = (bool)generic.Invoke(null, args);
var parsedValue = args[1];
}
}
static class TryParseExtensions
{
public static T Parse<T>(this string s) where T : IParsable<T>
{
return T.Parse(s, null);
}
public static bool TryParse<T>(this string? s, [MaybeNullWhen(false)] out T result) where T : IParsable<T>
{
result = default(T);
if (s == null) { return false; }
try
{
result = s.Parse<T>();
return true;
}
catch { return false; }
}
}
public class MyClass{
public int ForecastYear { get; set; }
}

Best way to define a method which can accept an Action or a Func delegate

I would like to introduce a method/function which can receive an Action or a Func<T>, and depending on what it got, it should return void or T.
Now I have to write this method in two, almost same versions like this.
public void WrapAction(Action action) {
// do something...
action();
// do something more...
}
public T WrapFunc(Func<T> func) {
// do something...
var result = func();
// do something more...
return result;
}
Is there any technique to avoid this repetition?
In contrast, for example in Javascript I have the flexibility to accept any kind of a function (may be void) and just return it's result, and if it was void, then it will return undefined. But in C# one cannot write something like Func<void>.
What about to make an Func<bool> out of an action via an extension method and reduce the wrapper to handle Func<T> only.
public static class ActionExtensions
{
public static Func<bool> ToFunc(this Action action)
{
return () =>
{
action();
return true;
};
}
}
Then WrapAction could simply call WrapFunc.
public void WrapAction(Action action)
{
WrapFunc(action.ToFunc());
}
Or remove WrapAction at all and use WrapFunc directly.
WrapFunc(action.ToFunc());
One possible solution is that you can extract the repeating bits out to separate methods in the same class so, something like this...
public void WrapAction(Action action) {
DoInitialBit();
action();
DoFinalBit();
}
public T WrapFunc(Func<T> func) {
DoInitialBit();
var result = func();
DoFinalBit();
return result;
}
private void DoInitialBit()
{
// Do the thing before you call the Action or Func
}
private void DoFinalBit()
{
// Do the thing after you call the Action or Func
}
Obviously, you may have to take inputs or return outputs from these additional methods as required but that's the general gist of it.
Some really ugly code to have code DRY:
static void Main(string[] args)
{
var p = new Program();
p.WrapAction(() => Console.WriteLine(123));
Console.WriteLine(p.WrapFunc<string>(() => "321"));
Console.ReadKey();
}
public void WrapAction(Action action) => WrapActionInner<object>(action);
public T WrapFunc<T>(Func<T> func) => WrapActionInner<T>(func);
private T WrapActionInner<T>(object action)
{
if (action is Action)
{
((Action)action)();
return default(T);
}
return ((Func<T>)action)();
}
The idea is to wrap functionality into type unsafe private method.

Delegate for any method type - C#

I want to have a class that will execute any external method, like this:
class CrazyClass
{
//other stuff
public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod)
{
//more stuff
return Method(ParametersForMethod) //or something like that
}
}
Is this possible? Is there a delegate that takes any method signature?
You can do this a different way by Func<T> and closures:
public T Execute<T>(Func<T> method)
{
// stuff
return method();
}
The caller can then use closures to implement it:
var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));
The advantage here is that you allow the compiler to do the hard work for you, and the method calls and return value are all type safe, provide intellisense, etc.
I think you are better off using reflections in this case, as you will get exactly what you asked for in the question - any method (static or instance), any parameters:
public object Execute(MethodInfo mi, object instance = null, object[] parameters = null)
{
return mi.Invoke(instance, parameters);
}
It's System.Reflection.MethodInfo class.
Kinda depends on why you want to do this in the first place...I would do this using the Func generic so that the CrazyClass can still be ignorant of the parameters.
class CrazyClass
{
//other stuff
public T Execute<T>(Func<T> Method)
{
//more stuff
return Method();//or something like that
}
}
class Program
{
public static int Foo(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
CrazyClass cc = new CrazyClass();
int someargs1 = 20;
int someargs2 = 10;
Func<int> method = new Func<int>(()=>Foo(someargs1,someargs2));
cc.Execute(method);
//which begs the question why the user wouldn't just do this:
Foo(someargs1, someargs2);
}
}
public static void AnyFuncExecutor(Action a)
{
try
{
a();
}
catch (Exception exception)
{
throw;
}
}

When are parameters in a lambda expression prefered?

This is kind of a weird question but it came up the other day and it has me thinking.
When is it preferable design to use lambda expressions in this form ".(x => x.Whatever)" verse ".(() => obj.Whatever)".
Consider the following extension methods.
public static class ExtensionMethods
{
public static string TryToGetTheString<T>(this T value, Func<T, string> method)
{
try
{
return method(value);
}
catch (Exception)
{
return "banana";
}
}
public static string TryToGetTheStringTwo<T>(this T value, Func<string> method)
{
try
{
return method();
}
catch (Exception)
{
return "banana";
}
}
}
And the following self referencing class.
public class testClass5000
{
private int? _id;
public int? ID { get { return _id; } set { _id = value; } }
private string _urgh;
public string Urgh { get; set; }
public testClass5000 tc5k { get; set; }
}
Then using an extremely lazy process to avoid checking for nulls, while attempting to get a string (Urgh) from testClass5000, you could implement the extension methods and class like such,
private void main()
{
var tc = new testClass5000();
textBox1.text = tc.TryToGetTheString(x => x.tc5k.tc5k.tc5k.Urgh);
}
However, since tc is declared locally the following also works.
private void main()
{
var tc = new testClass5000();
textBox1.text = tc.TryToGetTheStringTwo(() => tc.tc5k.tc5k.tc5k.Urgh);
}
I am curious when (x => x.tc5k.tc5k.tc5k.Urgh) is necessary and when (() => tc.tc5k.tc5k.tc5k.Urgh) is preferable.
//////////////////////////////////////////
I did come up with the following scenario where passing the parameter seems preferable.
With the following extension methods.
public static class ExtensionMethods
{
public static T TestOne<T>(this T value, Func<T, T> method)
{
try
{
return method(value);
}
catch (Exception)
{
return default(T);
}
}
public static T TestTwo<T>(this T value, Func<T> method)
{
try
{
return method();
}
catch (Exception)
{
return default(T);
}
}
}
And using the following code.
private void Form1_Load(object sender, EventArgs e)
{
var firstValue = 5;
var secondValue = 10;
var resultOne = firstValue.TestOne(x => x + 1).TestOne(x => x * 2);
//returns 12
var resultTwo = secondValue.TestTwo(() => secondValue + 1).TestTwo(() => secondValue * 2);
//returns 20
var resultThree = secondValue.TestTwo(() => secondValue.TestTwo(() => secondValue + 1) * 2);
//returns 22
}
In this example .TestOne(x => x + 1).TestOne(x => x * 2) is preferable notation because to achieve the same thing without passing a paremeter you need to start nesting expressions.
Injecting the parameters values directly in the lambda is more costly, because the compiler has to create a special class just for this purpose.
If we exclude performance considerations, then I would say that injecting the parameter is easier to write (personal preference here), and keeping the parameters in the prototype ( (x,y) => // do something) is useful when you're not actually the one providing the value of the parameters. For instance, when using the Select Linq query. Or I often use that for load balancing scenarios (a lambda "service => service.SomeFunction()", then a special factory retrieve the service and execute the lambda).
In cases where the parameters are simply not the same as the original value you provided.
A crude example
public static class Extensions
{
public static void DoSomething(this string s,Action<string> action)
{
var something = Enumerable.Range(1,100).Select(i=> String.Format("{0}_{1}",s,i));
foreach (var ss in something)
{
action(ss);
}
}
}
Then
var something = "ABC123";
something.DoSomething(x=>Console.WriteLine(x));
//Ignoring that we could do something.DoSomething(Console.WriteLine);
Obviously without the parameter you cant access the actual value you are insterested in, and the original value is of no use within this concept.

implicit or explicit conversion from T to T[]

Is there a way to implement a generic implicit or explicit converter for anything to an array of anything, something like this:
public static implicit operator T[](T objToConvert)
{
return new T[] { objToConvert };
}
No. The closest I can think of is an extension method:
public static T[] AsArray<T>(this T instance)
{
return new T[]{instance};
}
Use as:
var myArray = myInstnace.AsArray();
Note that you can omit the type name from the array constructor, which means the syntax is fairly clean, even with a long type name:
ReallyLongAndAwkwardTypeName value;
MethodThatTakesArray(new[] {value});
Operator overloading methods have to live inside the class they are overriding operators for (one side or the other). Since "T" is not defined, I don't see how this can be accomplished.
You can do it using normal method:
public static T[] ToArray<T>(T objToConvert) {
return new T[] { objToConvert };
}
I don't think you can define generics operator. Note, anyway, that the compiler is sufficient cleaver to guess the type of the generic param, so you can use:
var aString="";
var aStringArray=ToArray(aString);
aStringArray is defined as a string array even if you don't specify the generic param.
I was trying to think of situations where you might really use an implicit conversion to array. I started to wonder if many of the situations where you would want to do this could be alleviated by use of the params keyword.
The main situation that I could think of was that you had a single item of something and wanted to pass it to a function that takes an array as a parameter:
static void Main(string[] args)
{
string x = "I'm just a poor variable. Nobody loves me.";
Stickler.IOnlyTakeArrays_Rawr111(x); // won't go in! square peg, round hole, etc.
// *sigh* fine.
Stickler.IOnlyTakeArrays_Rawr111(new[] { x });
}
class Stickler
{
public static void IOnlyTakeArrays_Rawr111(string[] yum)
{
// ...
}
}
Hopefully in this situation the author of the method that you want to call has choosen to use the params keyword to allow you to pass your variable without wrapping it in an array:
class DataConcierge
{
public static T Create<T>(int id)
{
// ...
}
public static void Save<T>(params T[] items)
{
// ...
}
}
static void Main(string[] args)
{
var customer = DataConcierge.Create<Customer>(123);
// ...
DataConcierge.Save(customer); // this works!
//----------------------------------------------------
// or
//----------------------------------------------------
var customers = new Customer[]
{
DataConcierge.Create<Customer>(123),
DataConcierge.Create<Customer>(234),
DataConcierge.Create<Customer>(345),
};
// ...
DataConcierge.Save(customers); // this works too!
}
Of course, this doesn't really help you in situations where you need convert a variable to a single item array but not as a parameter to a method or in situations where the author of the method didn't use the params keyword.
But what kind of situation would the former be? Assigning an array to a property? Psh. How often does that happen?
And the latter? If the author didn't use the params keyword when they could have, then send them an email complaining about it. If the author is yourself, feel free to be extra belligerent in the email.
Hopefully you can tell that I'm being facetious. Seriously, though, are there any other common usage situations that you can think of where the params keyword would not be applicable?
** Disclaimer: I don't advocate excessive use of the params keyword. Use it if you think you should, but don't take my post to mean that you should always use the params keyword whenever you can.
In the past I've used the concept of a "Conductor" (my own name for it), which is just a class/struct that provides access to an underlying value.
The concept is useful for abstracting the access to a particular value retrieved from somewhere. For example, if you wanted to abstract access to a particular value in a dictionary, you could create a Conductor object that held a reference to the dictionary and the appropriate key for that value. You can also use this concept to easily implement rollback for serializable classes or for value types, though for that you'd need to add Rollback and Commit methods to the Conductor class/struct.
Below is an example of how you can use implicit conversions from T to Conductor and from Conductor to T[] in order to (sort of) achieve what you want.
static void Main(string[] args)
{
// implicit conversion here from Customer to Conductor<Customer>
Conductor<Customer> conductor = DataConcierge.Create<Customer>(123);
if (conductor.HasValue)
{
Console.WriteLine("I got a customer with Id {0}!", conductor.Value.Id);
// implicit conversion here from Conductor<Customer> to Customer[]
DataConcierge.Save<Customer>(conductor);
}
}
public struct Conductor<T> : IConductor<T>, IEquatable<T>, IEquatable<Conductor<T>>, IEquatable<IConductor<T>>
{
private T _Value;
public Conductor(T value)
{
this._Value = value;
}
public T Value
{
get { return this._Value; }
set { this._Value = value; }
}
public bool HasValue
{
get { return this._Value != null; }
}
public T GetValueOrDefault()
{
if (this.HasValue)
return this.Value;
else
return default(T);
}
public T GetValueOrDefault(T #default)
{
if (this.HasValue)
return this.Value;
else
return #default;
}
public bool TryGetValue(out T value)
{
if (this.HasValue)
{
value = this.Value;
return true;
}
else
{
value = default(T);
return false;
}
}
public T[] AsArray()
{
return new T[] { this._Value };
}
public static implicit operator Conductor<T>(T value)
{
return new Conductor<T>(value);
}
public static implicit operator T(Conductor<T> conductor)
{
return conductor.Value;
}
public static implicit operator T[](Conductor<T> conductor)
{
return conductor.AsArray();
}
public bool Equals(T other)
{
var otherEquatable = other as IEquatable<T>;
if (otherEquatable != null)
return otherEquatable.Equals(this.Value);
else
return object.Equals(this.Value, other);
}
public bool Equals(Conductor<T> other)
{
if (other.HasValue)
return this.Equals(other.Value);
else
return !this.HasValue;
}
public bool Equals(IConductor<T> other)
{
if (other != null && other.HasValue)
return this.Equals(other.Value);
else
return !this.HasValue;
}
public override bool Equals(object obj)
{
if (obj == null)
return !this.HasValue;
var conductor = obj as IConductor<T>;
if (conductor != null)
{
if (conductor.HasValue)
return this.Equals(conductor.Value);
else
return !this.HasValue;
}
return object.Equals(this.Value, obj);
}
public override int GetHashCode()
{
if (this.HasValue)
return this.Value.GetHashCode();
else
return 0;
}
public override string ToString()
{
if (this.HasValue)
return this.Value.ToString();
else
return null;
}
}

Categories

Resources