I have some code that is using a third-party library that I can't bypass. This library provides some auxiliary features that I need. At this time, my code is setup like this:
static Engine engine = new Engine();
static void Main(string[] args)
{
engine.Execute(MyCode);
}
private static void MyCode()
{
// my code goes here
}
Here's my challenge: I have to instantiate some code before MyCode can use it because that instantiation must hit a database and takes longer than the threshold allowed by Engine. I can't use a static variable because multiple instances will be necessary. Which basically means, I want something like this:
static Engine engine = new Engine();
static void Main(string[] args)
{
MyClass c = new MyClass();
c.Initialize(); // This is the db call
engine.Execute(MyCode); // This line is the problem
}
private static void MyCode(MyClass c)
{
// my code goes here
c.DoStuff();
}
My problem is, I basically need to create an overloaded method that takes a parameter. However, the Execute method in the third-party library doesn't let me do that. Is there some C# syntactial way I can do this that I'm missing?
You're looking for lambda expressions:
engine.Execute(() => MyCode(c));
I'm assuming that Engine.Execute takes an instance of Action.
You could make the MyCode function an instance member function on MyClass, then pass MyClass.MyCode to Engine.Execute as an Action.
public class Engine
{
public void Execute(Action action)
{
action.Invoke();
}
}
public class MyClass
{
public void Initialize()
{
System.Threading.Thread.Sleep(500); //Simulate some work.
}
public void Run()
{
// I've renamed it from MyCode to Run, but this method is essentially your
// my code method.
Console.WriteLine($"I'm being run from the engine! My Id is {_id}.");
}
private readonly Guid _id = Guid.NewGuid();
}
public static class Program
{
static void Main(string[] args)
{
var engine = new Engine();
var c = new MyClass();
c.Initialize();
engine.Execute(c.Run);
}
}
Related
class Program
{
static void Main(string[] args)
{
//I want to call the bird method here
}
public void bird(Program program)
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
How do I call bird in the main, I also tried to call the method from a object of the class but that didn't work
Does it even make sense to do this (I try to avoid static methods as much as possible).
If a method can be made static without changing the code, you should make it static. To answer your question though, you can create an instance of Program in your Main function and call the non-static methods through it.
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.bird();
}
public void bird()
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
Could do something like this
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var p = new Program();
p.bird(p);
}
public void bird(Program program)
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
Here, I wish to gain a delegate like function pointer, to point to a class method that's in another class (named Inner), and then pass it to a static function, like below:
public class Inner
{
public int M = 3;
public void F() { Console.WriteLine("f"); }
public void G() { Console.WriteLine("g"); }
}
class Program
{
public static void Caller(Action a)
{
a();
}
static void Main(string[] args)
{
var i = new Inner();
var f = i.F;
var g = i.G;
f();//error
g();//error
Program.Caller(f);
Console.WriteLine("Hello World!");
}
}
I'm from c/c++, and in c/c++, function pointer like this is very straight forward, but this C# code fail to compile. I googled and found almost all delegate explanations talks about delegate that points to class method inside itself.
My question is, how to fix the code to make it work?
Coding Seb's answer highlight's the cause of the issue, but doesn't really explain why.
It is because i.F is a method group, and not a specific method pointer. For example, imagine Inner was defined as so:
public class Inner
{
public void F() { Console.WriteLine("f"); }
public void F(string name) { Console.WriteLine(name); }
}
Which method would i.F refer to? F() or F(string)?
For that reason, you need to define the variable type explicitly, or cast the pointer:
Action f = i.F;
Or:
var f = (Action)i.F;
You can not set methods group in implicit variables in C# so if you just change 2 var in Action it's working
public class Inner
{
public int M = 3;
public void F() { Console.WriteLine("f"); }
public void G() { Console.WriteLine("g"); }
}
class Program
{
public static void Caller(Action a)
{
a();
}
static void Main(string[] args)
{
var i = new Inner();
Action f = i.F;
Action g = i.G;
f();
g();
Program.Caller(f);
Console.WriteLine("Hello World!");
}
}
Hi I have some code where I use a static object of Manager to call methods from Manager:
public class Manager
{
public static Manager sManager = new Manager();
public int x;
public Manager()
{
}
public void Modify()
{
x ++;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Manager.sManager.x);
Manager.sManager.Modify();
Console.WriteLine(Manager.sManager.x);
Console.ReadLine();
}
}
Is this a good way of accessing a method from Manager from outside or is there a better way if the class Manager must own the method Modify.
Would use of events in this case be a better way to build this and have Manager listen for an update?
Or is there a better way to handle this even if I want the method Modify to stay inside the Manager class?
It depends on the architecture you're trying to build.
Make everything static
If it's as simple as that, just make x and Modify static and you won't need an instance.
Use a singleton pattern
If you do need a Manager instance your code would be better using a Singleton pattern
private static Manager _manager;
public static Manager Manager
{
get
{
if (_manager == null)
{
_manager = new Manager();
}
return instance;
}
}
There is no reason here to create a static field of same type in the Manager class. You just need to create an object and then call the needed methods.
A more better way can be to make field private and just expose it for reading so that it can't be modified directly, and we only modify it by calling the modify() method:
public class Manager
{
private int x;
public int X
{
get
{
return x;
}
}
public Manager()
{
}
public void Modify()
{
x++;
}
}
and then in your Program class use it:
class Program
{
static void Main(string[] args)
{
Manager objManager = new Manager();
Console.WriteLine(objManager.X);
objManager.Modify();
Console.WriteLine(objManager.X);
Console.ReadLine();
}
}
Is there any way to set up a kind of observer to know if, within my app domain, a new object of a given X type is creates, I mean to detect when a class is instantiated.
What a would like to do (in a pink world) is something like the following:
public class BlackBoxObserver<T> where T : class
{
public event Action SomewhereBeyondYourSightAInstanceHasBeenCreated;
public void StartTracking()
{
//todo black magic...
}
protected virtual void OnSomewhereBeyondYourSightAInstanceHasBeenCreated()
=> SomewhereBeyondYourSightAInstanceHasBeenCreated?.Invoke();
}
And then using it:
private static void Main()
{
var dictionaryObserver = new BlackBoxObserver<Dictionary<string,string>>();
dictionaryObserver.StartTracking();
dictionaryObserver.SomewhereBeyondYourSightAInstanceHasBeenCreated +=
() => Console.WriteLine("Dictionary created somewhere!");
Console.ReadLine();
}
In C# , in Visual Studio, using a Console Application, is there a way to make methods in a class and call them in main program using readline?
Aka, a way to choose which methods to open when the program is running.
Easiest way is a switch statement for <4 cases, and a Dictionary for 4 or more cases.
class Program
{
private static IDictionary<string, Action> MethodMappings = new Dictionary<string, Action> {
{"Method1", Method1},
{"Method2", Method2},
...
}
public static void Main(string[] args) {
var methodCall = Console.ReadLine();
if (!MethodMappings.ContainsKey(methodCall)) {
//unrecognized command
}
MethodMappings[methodCall].Invoke();
}
private static void Method1() { ... }
private static void Method2() { ... }
}
This is very much possible using Reflection. Here is sample code to help you out:
class Program
{
public static void Hello1()
{
Console.WriteLine("\nHello 1");
}
public static void Hello2()
{
Console.WriteLine("\nHello 2");
}
static void Main(string[] args)
{
while (true)
{
String method = Console.ReadLine();
Type methodType = typeof(Program);
MethodInfo voidMethodInfo = methodType.GetMethod(method);
voidMethodInfo.Invoke(method,null);
}
}
}
For more information you can visit here.