So, I'm pretty much out of clues by now, not even sure if it's possible after all. I have a Visual C# Form, which gets run by the Program.cs (Standard way - VS did all the setup work of course).
In addition to that, I have a class with a static method in a seperate C# file, just because I like keeping one class in one file.
My form code has a public function:
public void print(String text)
{
rtb_log.appendText("\n" + text);
}
At a certain point of time, I'm calling the static function from the other class.
Is it possible, to actually access that print method from my other class? Since it's referring to rtb_log ( a rich text box), it's only availible if instanced, and of course not static. But since static methods can only access static members, I'm a little out of ideas here on how to append some text on my form from another class.
Any help here?
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables. Also, a static method can rewrite the values of any static data member.
Static methods are class methods, and non-static methods are methods that belong to an instance of the class. Static methods can access other static methods and variables without having to create an instance of the class.
You can call the method using object of the class or use static import simply.
Static methods are usually useful for operations that don't require any data from an instance of the class (from this ) and can perform their intended purpose solely using their arguments.
But since static methods can only access static members, I'm a little out of ideas here on how to append some text on my form from another class.
Static members can access instance members - they just need to know which instance to call the method on. So you could write:
public static void Foo(OtherForm myOtherForm)
{
// Do some stuff...
myOtherForm.Print(); // Case changed to comply with naming conventions
}
Then when you call the method, you need to supply a reference to the relevant form. Basically something has to determine which instance you want to call Print
on. Work out who has that information, and pass it on from there. I would recommend against using a static variable to hold this information. (Global state makes code less reusable, harder to reason about, and harder to test.)
EDIT: Given the comments, it sounds like you want:
// Within the form
private void HandleClick(object sender, EventArgs e)
{
SomeClass.StaticMethod(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With