I know there are a lot of threads talking about this but so far I haven't found one that helps my situation directly. I have members of the class that I need to access from both static and non-static methods. But if the members are non-static, I can't seem to get to them from the static methods.
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = Summary + " it didn't happen!";
}
}
public class MyMainClass
{
SomeCoolClass myCool = new SomeCoolClass();
myCool.DoSomeMethod();
SomeCoolClass.DoSomeOtherMethod();
}
How would you suggest I get Summary from either type of method?
How would you suggest I get Summary from either type of method?
You'll need to pass myCool to DoSomeOtherMethod - in which case you should make it an instance method to start with.
Fundamentally, if it needs the state of an instance of the type, why would you make it static?
You can't access instance members from a static method. The whole point of static methods is that they're not related to a class instance.
You simply can't do it that way. Static methods cannot access non static fields.
You can either make Summary static
public class SomeCoolClass
{
public static string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = SomeCoolClass.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = SomeCoolClass.Summary + " it didn't happen!";
}
}
Or you can pass an instance of SomeCoolClass to DoSomeOtherMethod and call Summary from the instance you just passed :
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = this.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod(SomeCoolClass instance)
{
string myInterval = instance.Summary + " it didn't happen!";
}
}
Anyway I can't really see the goal you're trying to reach.
Related
This question already has answers here:
CS0120: An object reference is required for the nonstatic field, method, or property 'foo'
(9 answers)
Closed 2 years ago.
I have to vrite an override function for my function DajGlos(), but I get back error CS0120 (An object reference is required for the non-static field, method, or property). How can I fix this?
My code:
static void Main(string[] args)
{
Pies pies = new Pies("Reksio", "ssaki", "lądowe", 50);
Pies.Przedstaw("Reksio", "ssaki", "lądowe");
Pies.DajGlos();
}
abstract class Zwierze
{
private static string Rodzina { get; set; }
private static string Grupa { get; set; }
private static string Imie { get; set; }
public static void Przedstaw(string Imie, string Rodzina, string Grupa)
{
Console.WriteLine("Jestem " + Imie + ", rodzina: " + Rodzina + ", grupa: " + Grupa);
}
public abstract void DajGlos();
}
class Pies : Zwierze
{
public Pies(string Imie, string Rodzina, string Grupa, int dlugoscOgona)
{
}
int dlugoscOgona;
public override void DajGlos()
{
Console.WriteLine("Bark!");
}
}```
ClassName.StaticMethodName(...) is for accessing static methods.
ObjectName.NonStaticMethodName(...) is for accessing non-static methods.
The line Pies.DajGlos(); is ClassName.NonStaticMethodName(...) which is not allowed.
I guess what you were trying to do is: pies.DajGlos();.
DajGlos is an instance method, so as the error message says, you need to call it on a specific instance (in your case - pies), not on the class itself. I.e.:
Pies pies = new Pies("Reksio", "ssaki", "lądowe", 50);
Pies.Przedstaw("Reksio", "ssaki", "lądowe");
pies.DajGlos(); // Here!
I am struggling to understand delegates and for that I created a simple example for myself but it doesn't work the way I want it to, here is my example:
my functions:
class Functions
{
public string MyFname(string MyString)
{
return MyString;
}
public string MyLname(string MyString)
{
return MyString;
}
}
delegate:
class DelClass
{
public delegate string StrDelegate(string OutPutString);
public void StringCon(StrDelegate Fname,StrDelegate Lname)
{
Console.WriteLine(Fname + " " + Lname);
}
}
Main:
class Program
{
static void Main(string[] args)
{
DelClass MyDel = new DelClass();
Functions MyTster = new Functions();
DelClass.StrDelegate Name = new DelClass.StrDelegate(MyTster.MyFname);
Name("SomeVariableName");
DelClass.StrDelegate Family = new DelClass.StrDelegate(MyTster.MyLname);
Family("SomeVariableFamilyName");
MyDel.StringCon(Name, Family);
}
}
The problem is Console window doesn't show my passed string instead it shows the undermentioned text:
MyDelegateMethodInMethod.DelClass+StrDelegate MyDelegateMethodInMethod.DelClass+
StrDelegate
And when I try to invoke the passed function in StringCon body like this:
Console.WriteLine(Fname() + " " + Lname();
The compiler complain that "Delegate 'StrDelegate' does not take 0 arguments" but I don't want to pass an argument in StringCon's passed parameters, I want to do it in my Main function, is this even possible with delegates?
A delegate is an object that contains a reference to a method. Invoking the delegate has the effect of executing the method. Your two methods each have a String parameter so to execute either of those methods you pass pass a single String argument. That means that, when you invoke your delegates, they need to pass a single String argument to the method they execute. Where do you think that value is going to come from? The delegate is not going to pluck it out of thin air. You have to pass it to the delegate when you invoke it. In this code:
public void StringCon(StrDelegate Fname,StrDelegate Lname)
{
Console.WriteLine(Fname + " " + Lname);
}
where are you doing that? You're not. You have to provide the arguments to the delegates in order for them to provide them to the methods:
public void StringCon(StrDelegate Fname,StrDelegate Lname)
{
Console.WriteLine(Fname("John") + " " + Lname("Doe"));
}
This is a very poor demonstration though, because your methods don't really do anything useful. How about defining a method does something useful like this:
public string GetFullName(string givenName, string familyName)
{
return givenName + " " + familyName;
}
and a corresponding delegate:
public delegate string FullNameGetter(string givenName, string familyName);
and then invoking it like so:
var fng = new FullNameGetter(GetFullName);
Console.WriteLine(fng("John", "Doe"));
If you do not want to pass a string as input, you should declare the delegates appropriately:
class DelClass
{
public delegate string StrDelegate();
public void StringCon(StrDelegate Fname,StrDelegate Lname)
{
Console.WriteLine(Fname() + " " + Lname());
}
}
From what you wrote, you want to save the string property somewhere - but the delegate is not the place to do it.You can create an object with FName, LName properties:
class Functions
{
public string MyFname() { return MyFnameProperty; }
public string MyLname() { return MyLnameProperty; }
public string MyFnameProperty { get; set; }
public string MyLnameProperty { get; set; }
}
And finally, in Main you will write:
class Program
{
static void Main(string[] args)
{
DelClass MyDel = new DelClass();
Functions MyTster = new Functions();
DelClass.StrDelegate Name = new DelClass.StrDelegate(MyTster.MyFname);
MyTster.MyFnameProperty ="SomeVariableName";
DelClass.StrDelegate Family = new DelClass.StrDelegate(MyTster.MyLname);
MyTster.MyLnameProperty = "SomeVariableFamilyName";
MyDel.StringCon(Name, Family);
}
}
This is not really how you should use delegates, delegates are mainly used as callback functions, or for EventHandlers, or when you like invoke a function.
an example of an EventHandler could be
public delegate void ReportErrorDelegate(object sender, MyCustomEventArgs e);
with a class
public class MyCustomEventArgs : EventArgs
{
// some implementation
public MyCustomEventArgs()
{
}
public MyCustomEventArgs(object argument)
: this()
{
....
}
}
and afterwards you could create an event which is based on your delegate as
public interface IRaiseMyCustomEventArgs
{
event ReportErrorDelegate CustomEventFired;
}
which you could then implement as
public class RaiseMyCustomEventArgs : IRaiseMyCustomEventArgs
{
public event ReportErrorDelegate CustomEventFired;
protected virtual void RaiseCustomEventArgs(object argument)
{
var local = CustomEventFired;
if (local != null) {
local.Invoke(this, new MyCustomEventArgs(argument));
}
}
}
an other option could be to recall a method after you detect that a UI interaction needs to be Invoked, like such
public delegate void SetTextDelegate(TextBox tb, string text);
public void SetText(TextBox tb, string text)
{
if (tb.InvokeRequired)
{
tb.Invoke(new SetTextDelegate(SetText), tb, text);
return;
}
tb.Text = text;
}
that would be called from a thread running inside a windows application (eg)
public void RunThread()
{
// assuming TextBox1 exists on the form
Thread t = new Thread(() => {
SetText(TextBox1, "Hello World");
});
t.Start();
}
I have a public class and need to use one of those variables inside a public static class. Is this possible? If so: how can I call it?
public class xmlData
{
public string testing;
}
public static class fileUpload
{
public static string uploadFile(string file)
// I want to use the testing here
}
You would inject an instance of the xmlData into the method. Like this:
public static string uploadFile(xmlData data, string file)
Now inside that method you can do this:
data.testing ...
To access instance field from static method is not possible. You can pass value as parameter:
public static string uploadFile(string file, string testing)
Or pass object into method:
public static string uploadFile(string file, xmlData data)
{ string testing = data.testing; }
of course it's possible. you just pass it in.
string myString = fileUpload.uploadFile(testing);
All of the methods I can think of in one single spot:
public class xmlData
{
public string testing;
// part of "first option"
public void RunStatic() {
fileUpload.uploadFile(testing);
}
}
public static class fileUpload
{
// used by "option 1, 3"
public static string uploadFile(string testing) {
var firstOption = testing;
}
// used by "option 2"
public static string uploadFile(xmlData myObject, string file) {
var secondOption = myObject.testing;
}
}
public class Program {
public static void Main() {
var objectExample = new xmlData();
// first example
objectExample.RunStatic();
// second example
fileUpload.uploadFile(objectExample, "");
// third example
fileUpload.uploadFile(objectExample.testing);
}
}
All of these will work and should hopefully answer the question. A different question might be whether or not its a good idea to expose instance variables directly or should a property be used. Hm.
Lets suppose we have these classes:
class A {
public string attr = "Class A";
public static void getAttribute(){
self currentClass = new self(); // equivalent to php
Console.Write("Attribute : " + currentClass.attr);
}
}
Class B : A {
public string attr = "Class B";
}
B = new B();
B.getAttribute();
I want B.getAttribute(); to print Attribute: Class B. How can I do this?
This is fundamentally impossible.
B.getAttribute() compiles to A.getAttribute().
I probably know what you are trying to do, but I have to tell you that this kind of PHP approach makes no sense in C#. I discourage you from using it.
public class A
{
private String attr = "Class A";
public static String getAttribute()
{
return (new A()).attr;
}
}
public class B : A
{
private String attr = "Class B";
public static String getAttribute()
{
return (new B()).attr;
}
}
You get the current class instance by the 'this' keyword. Obviously you cannot access that in a static method since by definition a static method executes without the context of a particular instance.
On the other hand, to access a member variable/property/method from inside the same class, you don't need the 'this' keyword at all, since it's implicit.
If you're asking how to do something like that in C#, I think the answer would be along these lines:
public class A
{
public virtual string attr
{
get { return "Class A" }
}
public void getAttribute(){
Console.Write("Attribute : " + attr);
}
}
public class B : A
{
public override string attr
{
get { return "Class B"; }
}
}
var b = new B();
b.getAttribute();
Regarding my comment in the other answer, if you needed getAttribute to be static, you could implement it this way:
public static void getAttribute(A obj){
Console.Write("Attribute : " + obj.attr);
}
You would then call it like this:
var b = new B();
A.getAttribute(b);
I know there are a lot of threads talking about this but so far I haven't found one that helps my situation directly. I have members of the class that I need to access from both static and non-static methods. But if the members are non-static, I can't seem to get to them from the static methods.
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = Summary + " it didn't happen!";
}
}
public class MyMainClass
{
SomeCoolClass myCool = new SomeCoolClass();
myCool.DoSomeMethod();
SomeCoolClass.DoSomeOtherMethod();
}
How would you suggest I get Summary from either type of method?
How would you suggest I get Summary from either type of method?
You'll need to pass myCool to DoSomeOtherMethod - in which case you should make it an instance method to start with.
Fundamentally, if it needs the state of an instance of the type, why would you make it static?
You can't access instance members from a static method. The whole point of static methods is that they're not related to a class instance.
You simply can't do it that way. Static methods cannot access non static fields.
You can either make Summary static
public class SomeCoolClass
{
public static string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = SomeCoolClass.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = SomeCoolClass.Summary + " it didn't happen!";
}
}
Or you can pass an instance of SomeCoolClass to DoSomeOtherMethod and call Summary from the instance you just passed :
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = this.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod(SomeCoolClass instance)
{
string myInterval = instance.Summary + " it didn't happen!";
}
}
Anyway I can't really see the goal you're trying to reach.