Using delegates with non static methods in C# - c#

Asking the same question as
Using delegates with non static methods [no picked answer]
so as to bring a closure to it.
So I use #Adam Marshall's solution, it works, but as soon as I start using it, i.e., Testit():
using System;
public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate;
public TestClass()
{
testDelegate = new TestDelegate(MyMethod);
}
public static void Testit()
{
testDelegate();
}
private virtual void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
It started to give the followig Error:
A object reference is required for the non-static field, method, or property
You can test it out here .
How to fix it? (Please fix it if possible instead of directing me to other posts, I've read them but am not able to understand them) Thx.

Either everything has to be static or everything has to be instance. You're getting in trouble because you are mixing and matching.
Everything static:
using System;
public class TestClass
{
private delegate void TestDelegate();
static TestDelegate testDelegate; //<-- static
static TestClass() //<-- static
{
testDelegate = new TestDelegate(MyMethod);
}
public static void Testit()
{
testDelegate();
}
private static void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
Everything instanced:
using System;
public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate;
public TestClass()
{
testDelegate = new TestDelegate(MyMethod);
}
public void Testit()
{
testDelegate();
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var t = new TestClass();
t.Testit(); //<-- non-static
}
}
Output (same in both examples):
Hello World
Foobar

You could use action C# internal delegate. This way you do not have specify the delegate. Then in your static method you could new up your object.
using System;
public class TestClass
{
Action testDelegate;
public TestClass()
{
testDelegate = new Action(MyMethod);
}
public static void Testit()
{
TestClass ts = new TestClass();
ts.testDelegate();
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
Output:
Hello World
Foobar

Related

How to call a non static method in the main?

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");
}
}

CS0103: I can't use methods through classes (basic level)

I'm trying to run a method created in a different class using the "public" access modifier. It seems not to be working like fields. Here's a simple example, could you lead me to a solution?
Thank you.
class Program
{
void Main(string[] args)
{
Hello();
}
}
class Example
{
public void Hello() //Error?
{
Console.WriteLine("Hello world");
}
}
You need to create an instance of the 'Example' class in able to call it's 'Hello' method:
class Program
{
void Main(string[] args)
{
var example = new Example();
example.Hello();
}
}
class Example
{
public void Hello() //Error?
{
Console.WriteLine("Hello world");
}
}
Or: make the Hello method static:
class Program
{
void Main(string[] args)
{
Example.Hello();
}
}
class Example
{
public static void Hello()
{
Console.WriteLine("Hello world");
}
}
just as an example: you need to instantiate an object of the class first to be able to access its members (unless they are static):
class Program
{
void Main(string[] args)
{
Example ex = new Example();
ex.Hello();
}
}
class Example
{
public void Hello()
{
Console.WriteLine("Hello world");
}
}

A way to store a method in a variable?

Hello I am new to programming.
Basically I need to store a method A from class A in variable A from class B inside a method from class B but I cannot seem to find a way.
To give an example:
Class A
public void methodA()
{
*method*
}
Class B
Delegate variableA; //I believe using Delegate is wrong
public void methodB();
{
variableA = ClassA.methodA();
}
Then in Class B there would be another method that will utilize the variable with the stored method.
public void methodC();
{
variableA;
}
This isn't the exact code I have but this is basically the gist of it. Any help is appreciated :)
Edit: Thanks for the help everyone!
ClassA definition:
public class ClassA
{
public void MethodA()
{
Console.WriteLine("Hello World!");
}
}
ClassB definition:
public class ClassB
{
private Action VariableA { get; set; }
public void MethodB(ClassA classA)
{
VariableA = classA.MethodA;
}
public void MethodC()
{
VariableA();
}
}
Program definition:
static void Main(string[] args)
{
ClassA classA = new ClassA();
ClassB classB = new ClassB();
classB.MethodB(classA);
classB.MethodC();
Console.ReadLine();
}
Here is an example:
public class Test
{
private Action<int> hiddenMethod = new Action<int>((i) =>
{
Console.WriteLine(i);
});
public void PublicMethod(int i)
{
hiddenMethod(i);
}
}
And using it:
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.PublicMethod(21);
Console.Read();
}
}
Use reflection:
public class A
{
public void MethodA()
{
Console.WriteLine("MethodA");
}
public static void StaticMethodA()
{
Console.WriteLine("StaticMethodA");
}
}
public class B
{
MethodInfo mv = typeof(A).GetMethod("MethodA");
MethodInfo smv = typeof(A).GetMethod("StaticMethodA");
public void CheckA(bool useStatic)
{
if (useStatic) smv.Invoke(null, null);
else mv.Invoke(new A(), null);
}
}
class MainClass
{
[STAThread]
public static void Main(string[] args)
{
var b = new B();
b.CheckA(true);
b.CheckA(false);
}
}
See details in MSDN.

Understanding generics and Func arguments

I would not be surprised if this has been answered somewhere, the problem is I am not sure how to phrase a search to find what I need. The things I have already found have either been too simplistic to be usable or poorly explained such that I cannot translate it into my own project. I had no formal instruction with event handlers, delegates, and the like (heck, I didn't even learn about Entity-Component Systems--or other design patterns--until long after I graduated college and was already employed as a programmer, and even then it wasn't something I learned at, or for, my job).
Essentially what I want to know is, what does the definition of Array.Sort<T>(T[] array, Comparison<T> comparison) look like?
There's clearly some kind of generalization going on, as myCompareDelegate(...) takes two arguments of any type. In almost everything I've found relating to Func arguments, a Func<> parameter requires explicitly declared types, with the exception of some sample code using an operator I am unfamiliar with:
SomeUtility(arg => new MyType());
public void SomeUtility<T>(Func<object, T> converter) {
var myType = converter("foo");
}
It compiles but I have no idea what it does and as such, I do not know how to utilize it to create code that will run or do what I want to do.
My goal here is to be able to create an event system (yes, I'm aware that C# has an event system built in, but again, all the sample code I've seen is either simplified to the point of uselessness--listeners contained in the same class as the dispatcher--or complicated and unexplained). I want the following to be true:
a single function to register an event listener (for any Type of event and its subtypes)
a single function to dispatch an event (calling only the relevant listeners)
to be able to create new event types without having to modify the functions for registration and handling (no explicit types in the dispatcher beyond the base event class) provided the new event type extends the allowable event type (i.e. an Entity will only dispatch EntityEvents not WorldEvents).
I have a system that works currently, but it requires that all my handlers pass through a single "onEvent" function which takes a base event object and figures out what it's actual type is, passing that off to the true handler.
Eg:
//Entity implements IEventDispatcher
public SomeConstructor(Entity ent) {
//public delegate void EventListener(EventBase eventData); is declared
//in the IEventDispatcher interface.
ent.attachEvent(typeof(EntityEventPreRender), new EventListener(onEvent));
ent.attachEvent(typeof(EntityEventPostRender), new EventListener(onEvent));
}
//EntityEventPreRender extends EntityEventRender extends EntityEvent extends EventBase
//EntityEventPostRender extends EntityEventRender extends EntityEvent extends EventBase
public void onEvent(EventBase data) {
if(data is EntityEventPreRender)
onPre((EntityEventPreRender)data);
if(data is EntityEventPostRender)
onPost((EntityEventPostRender)data);
}
public void onPre(EntityEventPreRender evt) {}
public void onPost(EntityEventPostRender evt) {}
attachEvent() here is a function that takes a Type (used as a HashMap key) and a Delegate and stores it in a list (the HashMap value). Dispatching the event just needs to pass the EventData object, which is queried for its type (via evt.GetType()) to retrieve the list of listeners, then invoking them: listItem(evt)
But I'd rather be able to just do this:
public SomeConstructor(Entity ent) {
ent.attachEvent(onPre);
ent.attachEvent(onPost);
}
public void onPre(EntityEventPreRender evt) {}
public void onPost(EntityEventPostRender evt) {}
But I cannot, for the life of me, figure out how to do this because I do not know how to declare the attachEvent() function to take a generic function parameter the way Array.Sort<T>(T[] array, Comparison<T> comparison) does. I get the error:
"The type arguments for method doSomething<T>(SomeClass.Thing<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly."
I think you might be looking for something like the following:
public static class PubSub<TMessage>
{
private static List
<
Action
<
TMessage
>
> listeners = new List<Action<TMessage>>();
public static void Listen(Action<TMessage> listener)
{
if (listener != null) listeners.Add(listener);
}
public static void Unlisten(Action<TMessage> listener)
{
if (listeners.Contains(listener)) listeners.Remove(listener);
}
public static void Broadcast(TMessage message)
{
foreach(var listener in listeners) listener(message);
}
}
In the above code, using PubSub and specifying a type for TMessage creates a new static class in memory with its own memory space allocated for storing a separate list of listeners. The compiler will ensure that only the substituted type for TMessage and its subclasses will be allowed in that list, provided you consistently use the base type as the type argument for the TMessage type parameter.
You would then use it like so:
public class SomeMessageType
{
public int SomeId;
public string SomeDescription;
}
public class SomePublisher
{
public void DoSomethingCool(string description)
{
var randomizer = new Random();
...
PubSub<SomeMessageType>.Broadcast(new SomeMessageType(){SomeId = randomizer.Next(), SomeDescription = description});
}
}
public class SomeListener
{
static SomeListener()
{
PubSub<SomeMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeMessageType message)
{
// do something with the message
}
}
If you then create another class SomeOtherMessageType which does not inherit from SomeMessageType and make similar calls to it, it will only broadcast to listeners of that specific type.
EDITED:
Here is a full proof of concept that compiles that you can run in a console app to allay any remaining concerns you may have over efficacy of this technique.
using System;
using System.Collections.Generic;
namespace TestPubSub
{
public class Program
{
public static void Main(string[] args)
{
Program.startListeners();
Program.sendTestMessages();
Program.stopConsoleFromExitingImmediately();
}
private static void startListeners()
{
SomeListener.Listen();
SomeOtherListener1.Listen();
SomeOtherListener2.Listen();
}
private static void sendTestMessages()
{
var publisher1 = new SomePublisher();
var publisher2 = new SomeOtherPublisher();
publisher1.DoSomethingCool("Hello world");
publisher2.DoSomethingElse(DateTime.Now);
}
private static void stopConsoleFromExitingImmediately()
{
Console.ReadKey();
}
}
public static class PubSub<TMessage>
{
private static List
<
Action
<
TMessage
>
> listeners = new List<Action<TMessage>>();
public static void Listen(Action<TMessage> listener)
{
if (listener != null) listeners.Add(listener);
}
public static void Unlisten(Action<TMessage> listener)
{
if (listeners.Contains(listener)) listeners.Remove(listener);
}
public static void Broadcast(TMessage message)
{
foreach(var listener in listeners) listener(message);
}
}
public class SomeMessageType
{
public int SomeId;
public string SomeDescription;
}
public class SomeOtherMessageType
{
public DateTime SomeDate;
public Double SomeAmount;
}
public class SomePublisher
{
public void DoSomethingCool(string description)
{
var randomizer = new Random();
PubSub<SomeMessageType>.Broadcast(new SomeMessageType(){SomeId = randomizer.Next(), SomeDescription = description});
}
}
public class SomeOtherPublisher
{
public void DoSomethingElse(DateTime when)
{
var randomizer = new Random();
PubSub<SomeOtherMessageType>.Broadcast(new SomeOtherMessageType(){SomeAmount = randomizer.NextDouble(), SomeDate = when});
}
}
public class SomeListener
{
public static void Listen()
{
PubSub<SomeMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeMessageType message)
{
Console.WriteLine("Attention! SomeMessageType receieved by SomeListener with\r\nid: {0}\r\ndescription: {1}\r\n", message.SomeId, message.SomeDescription);
}
}
public class SomeOtherListener1
{
public static void Listen()
{
PubSub<SomeOtherMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Heads up! SomeOtherMessageType receieved by SomeOtherListener1 with\r\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
public class SomeOtherListener2
{
public static void Listen()
{
PubSub<SomeOtherMessageType>.Listen(SomeMessageEvent);
}
private static void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Yo! SomeOtherMessageType receieved by SomeOtherListener2 withr\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
}
EDITED AGAIN (Alternate proof of concept using an instance based pubs):
Here is a proof of concept using an instance based PubSub.
using System;
using System.Collections.Generic;
namespace TestPubSub
{
public class Program
{
private static PubSub<SomeMessageType> pubSub1 = new PubSub<SomeMessageType>();
private static PubSub<SomeOtherMessageType> pubSub2 = new PubSub<SomeOtherMessageType>();
private static SomeListener listener1 = new SomeListener();
private static SomeOtherListener1 listener2 = new SomeOtherListener1();
private static SomeOtherListener2 listener3 = new SomeOtherListener2();
public static void Main(string[] args)
{
Program.startListeners();
Program.sendTestMessages();
Program.stopConsoleFromExitingImmediately();
}
private static void startListeners()
{
Program.listener1.Listen(Program.pubSub1);
Program.listener2.Listen(Program.pubSub2);
Program.listener3.Listen(Program.pubSub2);
}
private static void sendTestMessages()
{
var publisher1 = new SomePublisher(Program.pubSub1);
var publisher2 = new SomeOtherPublisher(Program.pubSub2);
publisher1.DoSomethingCool("Hello world");
publisher2.DoSomethingElse(DateTime.Now);
}
private static void stopConsoleFromExitingImmediately()
{
Console.ReadKey();
}
}
public class PubSub<TMessage>
{
private List
<
Action
<
TMessage
>
> listeners = new List<Action<TMessage>>();
public void Listen(Action<TMessage> listener)
{
if (listener != null) this.listeners.Add(listener);
}
public void Unlisten(Action<TMessage> listener)
{
if (listeners.Contains(listener)) this.listeners.Remove(listener);
}
public void Broadcast(TMessage message)
{
foreach(var listener in this.listeners) listener(message);
}
}
public class SomeMessageType
{
public int SomeId;
public string SomeDescription;
}
public class SomeOtherMessageType
{
public DateTime SomeDate;
public Double SomeAmount;
}
public class SomePublisher
{
private PubSub<SomeMessageType> pubSub;
public SomePublisher(PubSub<SomeMessageType> pubSub) { this.pubSub = pubSub; }
public void DoSomethingCool(string description)
{
var randomizer = new Random();
this.pubSub.Broadcast(new SomeMessageType(){SomeId = randomizer.Next(), SomeDescription = description});
}
}
public class SomeOtherPublisher
{
private PubSub<SomeOtherMessageType> pubSub;
public SomeOtherPublisher(PubSub<SomeOtherMessageType> pubSub) { this.pubSub = pubSub; }
public void DoSomethingElse(DateTime when)
{
var randomizer = new Random();
this.pubSub.Broadcast(new SomeOtherMessageType(){SomeAmount = randomizer.NextDouble(), SomeDate = when});
}
}
public class SomeListener
{
public void Listen(PubSub<SomeMessageType> pubSub)
{
pubSub.Listen(this.SomeMessageEvent);
}
private void SomeMessageEvent(SomeMessageType message)
{
Console.WriteLine("Attention! SomeMessageType receieved by SomeListener with\r\nid: {0}\r\ndescription: {1}\r\n", message.SomeId, message.SomeDescription);
}
}
public class SomeOtherListener1
{
public void Listen(PubSub<SomeOtherMessageType> pubSub)
{
pubSub.Listen(this.SomeMessageEvent);
}
private void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Heads up! SomeOtherMessageType receieved by SomeOtherListener1 with\r\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
public class SomeOtherListener2
{
public void Listen(PubSub<SomeOtherMessageType> pubSub)
{
pubSub.Listen(this.SomeMessageEvent);
}
private void SomeMessageEvent(SomeOtherMessageType message)
{
Console.WriteLine("Yo! SomeOtherMessageType receieved by SomeOtherListener2 withr\namount: {0}\r\ndate: {1}\r\n", message.SomeAmount, message.SomeDate);
}
}
}

Static int main issue

This is a Console Program
Scenario:
I have a many function in my c# code and is set to be Public and Private. And I have static int Main(string args[]) of course. In int Main i calling some function Public and Private and thats interupting the function when i debug that. It says if main was static so all function must be static, yet my code in function Public and Private must be have "that" function. If i change static int Main with my public int main, debug cant be done because int Main must be static.
First im saying i really sorry for giving a non-understable question
If that's so confusing understanding my scenario, see my Example Code Here
namespace Example
{
class Program
{
public class ClassInPublic
{
public int Num;
public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private void Foo()
{
DeclaringInstance.Num = 35;
DeclaringInstance.Sentence = "Hello World";
Console.Write("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class");
}
static int Main(string args[])
{
Foo();
}
}
}
That's my case
And with help from others i already build this
namespace Example
{
class Program
{
public static class ClassInPublic
{
public int Num;
public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private static void Foo()
{
DeclaringInstance.Num = 35;
DeclaringInstance.Sentence = "Hello World";
Console.Write("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private static void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class");
}
public static int Main(string args[])
{
Foo();
}
}
}
Error sign is lower right now, the rest is the ClassInPublic
It says i cannot declare
cannot declare instance members in static class
May someone assist me to overcome this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example
{
class Program
{
public void foo()
{
Console.WriteLine("This is foo in Class Program");
}
static void fooStatic()
{
Console.WriteLine("This is Static foo");
}
static void Main(string[] args)
{
Program fooInstance = new Program();
fooStatic();
fooInstance.foo();
}
}
}
Here is a small example. Static functions are one per class. When you make public or private function they exist for each instance.
Edit:
Here is what I think you are trying to do:
namespace Example
{
class Program
{
public class ClassInPublic
{
static public int Num;
static public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private static void Foo()
{
ClassInPublic.Num = 35;
ClassInPublic.Sentence = "Hello World";
Console.WriteLine("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private static void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class\n");
}
public static int Main(string[] args)
{
Foo();
return 0;
}
}
}

Categories