using object in multiple function - c#

How can i use object from one function in another ?
main()
{
private void button1_click {
MyClass object = new MyClass();
object.blabla();
}
private void button2_click {
// how can i use object from button1_click ??
}
}

By storing the object out of the scope of a function.
main()
{
MyClass obj;
private void button1_click
{
obj = new MyClass();
obj.blabla();
}
private void button2_click
{
//maybe check for null etc
obj.dosomethingelse();
}
}

basically this is a more fundamental question, which can be solved as eg
class program
{
void Main(string[] args)
{
private MyClass FooInstance;
private void button1_click()
{
// TODO be defensive: check if this.FooInstance is assigned before, to not override it!
this.FooInstance = new MyClass();
this.FooInstance.blablabla();
}
private void button2_click()
{
// TODO add some null check aka make sure, that button1_click() happened before and this.FooInstance is assigned
this.FooInstance = ....;
}
}
}
you may also choose lazy-loading as an option (mentioned by Andrew Anderson)

make object as member variable of the class where functions are defined.
main()
{
private MyClass object;
private void button1_click {
object = new MyClass();

Related

Should local variables be used in lambda statements when passed as delegates?

If I have a method that takes an argument of type Action, for example:
public void Foo(Action bar)
{
bar?.Invoke();
}
And I wish to pass it a lambda that uses a local variable, e.g.:
private void SomeEvent(object sender, SomeEventArgs e)
{
foo(() => { e.Cancel = true; });
}
Will this lambda execute as expected with respect to the use of the local variable, in this case, e? What I mean is, When foo() is called and in turn attempts to call the lambda, will it know e? Or will e be out of scope and I should do something like the following instead?
private void SomeEvent(object sender, SomeEventArgs e)
{
foo((SomeEventArgs a) => { a.Cancel = true; }, e);
}
public void Foo(Action<SomEventArgs> bar, SomeEventArgs e)
{
bar?.Invoke(e);
}
This little example shows that the local variable will be changed:
void Main()
{
int local = 0;
Foo(() => { local = 55; });
Console.WriteLine(local);
}
public static void Foo(Action bar)
{
bar?.Invoke();
}
Output:
55
This example can also be extended to include events:
public class P
{
public delegate void MyEventDelegate(bool e);
public event MyEventDelegate MyEvent;
public void shootEvent() {MyEvent(false);}
}
void Main()
{
P p = new P();
p.MyEvent += MyeventHandler;
p.shootEvent();
}
public void MyeventHandler(bool b)
{
Foo(() => { b = true; });
Console.WriteLine(b);
}
Output:
true
Yes, it should work as expected. This is called "Variable capture", and is very well explained here.
In your example, the e variable is captured, so it won't go out of scope.

Why is the GetServer() method returning null?

today I face an issue with some code I have written and really don't know where I have gone wrong, I'll keep it short and sweet basically the GetServer() method in the Faze class is returning null and I am really not sure why, but I was hoping you guys could help me with that.
I have left a few code snippets below of each class involved in the issue and where its initially called to give you a better idea on where things are going wrong.
Program.cs entry point..
static void Main(string[] args)
{
XmlConfigurator.Configure();
Faze.run();
while (true)
Console.ReadKey();
}
Faze class
public static class Faze
{
private static FazeServer fazeServer;
public static void run()
{
Console.Title = "Loading...";
fazeServer = new FazeServer("");
}
public static FazeServer GetServer()
{
return fazeServer;
}
}
FazeServer class
public sealed class FazeServer
{
private ConsoleWorker consoleWorker;
public FazeServer(string lol)
{
LoadServer();
}
private void LoadServer()
{
consoleWorker = new ConsoleWorker();
classLogger.Info("Server has been loaded.");
}
}
ConsoleWorker class
class ConsoleWorker : IDisposable
{
private readonly Timer consoleWorkerTimer;
private readonly int consoleWorkerInterval;
private static ILog classLogger;
public ConsoleWorker()
{
if (Faze.GetServer() == null)
throw new Exception("Server null..");
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
consoleWorkerTimer = new Timer(TimerElapsed, null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));
classLogger = LogManager.GetLogger(typeof(ConsoleWorker));
}
private void TimerElapsed(object timerObject)
{
// Do something...
}
public void Dispose()
{
consoleWorkerTimer.Dispose();
}
}
After following the trace, the code that interrupts it is my null check
if (Faze.GetServer() == null)
throw new Exception("Server null..");
Before I added the if statement the line that caused an exception was
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
Why is GetServer() returning null, can anyone help?
I am after a few beers but in the class 'Faze' you have implemented a static field: 'fazeServer' and did not assign a value to it - therefore it is null.
If you would like to assign a value to 'fazeServer' static field please implement in example a static constructor for the class 'Faze' - in example: '
static Faze() { fazeServer = new FazeServer("whatEverString");}'
and that should solve the NRE.
Regards,
P.Sz.
Class fields are initialized to null by default so your code is the equivalent of:
public static class Faze
{
private static FazeServer fazeServer = null;
public static FazeServer GetServer() => fazeServer;
}
of course, calling GetServer() will return the unchaged value which is null.
If you want to initialize it yourself, use a static constructor:
public static class Faze
{
private static FazeServer fazeServer;
static Faze()
{
fazeServer = new FazeServer("");
}
}
or the field initializer:
public static class Faze
{
private static FazeServer fazeServer = new FazeServer("");
}
So it will be certain that you will get an instance when you call GetServer().
You're calling GetServer() before a value has been set in the fazeServer static variable.
The call stack is as follows:
fazeServer = new FazeServer("");
- LoadServer();
- - consoleWorker = new ConsoleWorker();
- - - if (Faze.GetServer() == null)
Or, in plain English:
fazeServer is set to the return value of new FazeServer()
new FazeServer() internally calls LoadServer()
LoadServer() internally calls new ConsoleWorker()
new ConsoleWorker() internally calls Faze.GetServer()
Faze.GetServer() returns the current value of fazeServer
So the code which sets that static variable is internally trying to read that static variable before it has finished setting it.

Avoiding null pointer exception in delegates

I'm using delegates
in my c# windows forms application project.Using that I'm trying to remove items in a list box. I'm getting this null pointer exception and can somebody suggest a way to avoid that?
Delegate
public delegate void OrderEventDelegate (Object sender, OrderEventArgs args);
OrderEventArgs class
public class OrderEventArgs
{
private String message;
public String Message
{
get { return message; }
set { message = value; }
}
private int tableNo;
public int TableNo
{
get { return tableNo; }
set { tableNo = value; }
}
}
Class 1
public partial class Class1 : Form
{
private event OrderEventDelegate readyEvent;
public Class1(HomeForm parent, int tableNo)
{
InitializeComponent();
readyEvent -= new OrderEventDelegate(parent.readyOrder);
}
public void button_click()
{
OrderEventArgs readyOrderArg = new OrderEventArgs();
readyOrderArg.TableNo = 1;
readyOrderArg.Message = "123";
readyEvent(this, readyOrderArg);
}
}
Here readyEvent -= new OrderEventDelegate(parent.readyOrder);readyOrder() is the method which remove items in the list, which is located in the 'Homeform'.
Exception
It is possible to initialize C# events with an empty delegate. This way it can always be called safely without a null pointer check. As shown in this answer: https://stackoverflow.com/a/340618/2404788.
public delegate void OrderEventDelegate (Object sender, OrderEventArgs args) = delegate {};
If there's a possibility of something being null and you can do something about it/don't want to critically fail when it is, then check for it:
if (readyEvent != null) {
readyEvent( ... );
}
But the point here, I suppose, is that you don't want this thing to be null; so you should subscribe a handler to the event. I'm not sure why you're trying to remove a new instance of the delegate handler, but to add one you would use +=.

Why is subscribed event always null?

I declare a subscription to event in:
public class MainClass
{
public void btndel_bar_Click(object sender, RoutedEventArgs e)
{
SomeClass sc = new SomeClass();
sc.FieldUpdate += new SomeClass.FieldUpdateHandler(sc_FieldUpdate);
}
void sc_FieldUpdate(object sender, ValueEventArgs e)
{
MessageBox.Show(e.Smth_property);
}
}
And here is I want to listen event:
public class Someclass
{
public delegate void FieldUpdateHandler(object sender, ValueEventArgs e);
public event FieldUpdateHandler FieldUpdate;
void Somemethod()
{
string str = "Steel";
ValueEventArgs args = new ValueEventArgs(str);
FieldUpdate(this, args);
}
}
A class which carries data:
public class ValueEventArgs : EventArgs
{
private string smth;
public ValueEventArgs(string smth)
{
this.smth = smth;
}
public string Smth_property
{
get { return smth; }
}
}
I always have FieldUpdate=null. How to solve it?
You're calling Somemethod() in the constructor, before the calling code gets a chance to add the event handler.
Therefore, the event is still null.
The moment you create the object of SomeClass your event would get reinitialized.
Make your event a static so that multiple objects of SomeClass would share it
public static event FieldUpdateHandler FieldUpdate;
I've read articles about delegates and events and after reading I always I thought to make all operations again. I did all over again and it works! Consequently I done something wrong when I did at the beginning of.

What does the keyword this mean in C#, when talking about event handlers?

When I write an event handler for csharp, it looks like this:
public void FooHandler(object sender, EventArgs e)
{
//do stuff..
this.doSomething(); //Does the "this" keyword mean something in this context?
}
Does the "this" keyword mean something in this context?
EDIT:
Let's say I also have this code:
public class GizmoManager {
public void Manage() {
g = new Gizmo();
g.Foo += new EventHandler(FooHandler);
}
}
What would the this (within FooHandler) refer to?
Yes, it's a reference to object for which FooHandler() is called. Delegates are capable of referencing both static and non-static methods. When talking about non-static ones, this is a reference to object instance.
class A
{
public delegate void MyDelegate(object sender, int x);
public event MyDelegate TheEvent;
public void func()
{
if(TheEvent != null) TheEvent(this, 123);
}
}
class B
{
public B()
{
A a = new A();
a.TheEvent += handler;
a.func();
}
public void handler(object sender, int x)
{
// "sender" is a reference to object of type A that we've created in ctor
// "x" is 123
// "this" is a reference to B (b below)
}
}
B b = new B(); // here it starts
Some more details. Your code:
g = new Gizmo();
g.Foo += new EventHandler(FooHandler);
could be re-written like this
g = new Gizmo();
g.Foo += new EventHandler(this.FooHandler); // look here
In this case this is the same this that you have in your handler ;-)
And even more, if you have some problems with understanding this:
class X
{
int a;
public X(int b)
{
this.a = b; // this stands for "this object"
// a = b is absolutely the same
}
public X getItsThis()
{
return this;
}
}
X x = new X();
X x2 = x.getItsThis();
// x and x2 refer to THE SAME object
// there's still only one object of class X, but 2 references: x and x2
more complete...
public class Bar
{
public Bar()
{
Gizmo g = new Gizmo();
g.Foo += new EventHandler(FooHandler);
}
public void FooHandler(object sender, EventArgs e)
{
//do stuff..
this //Does the "this" keyword mean something in this context?
}
}
"this" will refer to an instance of Bar
this is going to refer to the current class you are in, not the method.
From MSDN,
The this keyword refers to the current instance of the class. Static
member functions do not have a this pointer. The this keyword can be
used to access members from within constructors, instance methods, and
instance accessors.
In your example, this.doSomething() refers to a method in some arbitrary class outside of that method. this is redundant.
It is useful to use this in cases like this:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
It helps delineate between the meaning. Otherwise, without this what name or alias are you really referring to?
Finally, sender is going to refer to the object which raised the event.

Categories

Resources