JibW
JibW

Reputation: 4562

C# Pass Class as parameter to method and call static method in there

I am new to C# and looking the best way to do the following implementation.

My project got several Model classes (like 25) and each class got a static method called "process()", which just takes a bit of time to finish it's task.

I need to call all these method in each class one after another and to add some logs (write status of method execution in to file) to track execution.

I can simply do the following, But surely there should be a better professional way to do this

Log.WriteLog(DateTime.Now + " Class A Process Started");
ClassA.Process()
Log.WriteLog(DateTime.Now + " Class A Process Finished");
Log.WriteLog(DateTime.Now + " Class B Process Started");
ClassB.Process()
Log.WriteLog(DateTime.Now + " Class B Process Finished");
............ continue 25 classes

What I am trying to do is to write a method and just Add Logs and repetitive work in there..

private void CommonMethod(Class)
{
   Check what class
   Add Process started Log
   Call Process method
   Add proicess finished Log
}

Upvotes: 2

Views: 3981

Answers (4)

MStew
MStew

Reputation: 1275

Here's another suggestion:

class Program
{
    static void Main(string[] args)
    {
        var x = new Calculate { a = 1, b = 2 };
        var y = new Calculate { a = 10, b = 20 };
        var z = new Calculate { a = 100, b = 200 };

        var calculations = new List<Calculate>{
            new Calculate() { a = 1, b = 2 },
            new Calculate() { a = 10, b = 20 },
            new Calculate() { a = 100, b = 200 }
        };

        calculations.ForEach(c =>
        {
            c.Process();
        });
    }
}

class Calculate
{
    public int a { get; set; }
    public int b { get; set; }

    public void Process()
    {
        Console.WriteLine(a + b);
    }
}

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52808

You could create function that takes a delegate and performs the logging, something like this:

public void ProcessAndLog(Action action, String processName)
{
  Log.WriteLog(DateTime.Now + $" Class {processName} Process Started");
  action();
  Log.WriteLog(DateTime.Now + $" Class {processName} Process Finished");
}

and call it like so:

ProcessAndLog(ClassA.Process, "A"); //"A" could be part of ClassA - e.g. ClassA.Name;
ProcessAndLog(ClassB.Process, "B");
//etc

This will work so long as every Process method has no params and retuns void - the signature of the Action delegate.

If it has parameters, you can call it like so:

ProcessAndLog(() => ClassC.Process("value"), "C");

If you need a return value, consider a Func<T> instead of Action.

Upvotes: 5

Philippe Par&#233;
Philippe Par&#233;

Reputation: 4418

Static interfaces don't exist in C#. The only way to reference a static member of a class is by its class name and member name.

An alternative would be to use reflection. Get the static method by it's string name and invoke it. Like this:

static void CommonMethod(Type type)
{
    MethodInfo methodInfo = type.GetMethod("TheStaticMethodName");

    if (methodInfo != null)
    {
        methodInfo.Invoke(null, new object[0]);
    }
}

//Invoke it like this
CommonMethod(typeof(MyStaticType));

The first parameter for Invoke is the target. For an instance method you would pass a class instance you want to invoke on, but for static members just put null.

The second parameter is the arguments. You can put an empty array the if there's no arguments.

Also, you could have the same method with a generic type like this:

static void CommonMethod<T>()
{
    MethodInfo methodInfo = typeof(T).GetMethod("TheStaticMethodName");

    if (methodInfo != null)
    {
        methodInfo.Invoke(null, new object[0]);
    }
}

Note that generics aren't always the best since they generate a lot of stuff at compile time.

Upvotes: 1

Zein Makki
Zein Makki

Reputation: 30052

You can do this:

private void CommonMethod<T>()
{
    //Add Process started Log
    //Call Process method
    typeof(T).GetMethod("process")?.Invoke(null, null); // not target needed
    //Add proicess finished Log
}

Usage:

CommonMethod<ClassA>();
CommonMethod<ClassB>();

Upvotes: 1

Related Questions