Reputation: 604
Apologies if this sounds complex my vocab isn't fully with me today.
I have an method where I want to use .click Example
middle.click();
But I also have another
end.click();
What if I want to pass either "middle" or "end" as a parameter, is it possible to do so
MethodGo(string usedforSomethingElse, Func<string> thisMethod)
{
thisMethod.click();
}
Upvotes: 1
Views: 38
Reputation: 470
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
public interface IMyClick
{
string click();
}
}
--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
public class Middle : IMyClick
{
public string click()
{
return "Middle Click";
}
}
}
---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
public class End :IMyClick
{
public string click()
{
return "End Click";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Student;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IMyClick m1 = new Middle();
IMyClick e1 = new End();
string result = MethodtoGo(m1);
Console.WriteLine(result);
Console.Read();
}
static string MethodtoGo(IMyClick cc)
{
return cc.click();
}
}
}
in the above code now you can pass the Middle or End class instance as both are implementing the same interface. string result = MethodtoGo(m1); The MethodToGo has one parameter of type interface, that mean any class that is implementing the interface can be pass as input to the method.
hope this helps.
Upvotes: 0
Reputation: 180808
It would have to look more like this:
MethodGo(string usedforSomethingElse, ISomeObjectWithClickMethod thisObject)
{
thisObject.click();
}
Or, you could do this:
MethodGo(string usedforSomethingElse, Func<string> thisMethod)
{
thisMethod();
}
Upvotes: 2