c# Methods error CS0236 [duplicate] - c#

This question already has answers here:
A field initializer cannot reference the nonstatic field, method, or property
(6 answers)
Closed 5 years ago.
Guys i need some help here,
i have error in
Line 50: CS0236 C# A field initializer cannot reference the non-static field, method, or property
Line 51: CS0236 C# A field initializer cannot reference the non-static field, method, or property
namespace ConsoleApplication5
{
public delegate string Metodo(string t1, string t2);
class Program
{
static void Main(string[] args)
{
}
}
public class ExemploDel
{
public static string NomeMetodo(string t1, string t2)
{
return t1 + t2;
}
Metodo meuMetodo = NomeMetodo;
}
public class Metodos
{
public string Method1(string tx1, string tx2)
{
return tx1 + tx2;
}
public string Method2(string tx1, string tx2)
{
return tx2 + tx1;
}
}
public class DelegatesEx
{
public static string NomeMetodo(string t1, string t2)
{
return t1 + t2;
}
Metodos obj = new Metodos();
Metodo m1 = obj.Method1;
Metodo m2 = obj.Method2;
Metodo m3 = NomeMetodo;
}
}

First of all, you have placed the calling code at wrong place, the following 4 lines should go in the Main method of your program:
Solution1:
class Program
{
static void Main(string[] args)
{
Metodos obj = new Metodos();
Metodo m1 = obj.Method1;
Metodo m2 = obj.Method2;
Metodo m3 = NomeMetodo;
}
}
Secondly, you have marked your delegate as static while you are trying to assign it instance method, so either make the delegate non-static in declaration and make the methods static.
public delegate string Metodo(string t1, string t2);
Solution2:
if you want to keep the Metodo delegate static, then your methods should also be satic like:
public class Metodos
{
public static string Method1(string tx1, string tx2)
{
return tx1 + tx2;
}
public static string Method2(string tx1, string tx2)
{
return tx2 + tx1;
}
}
and now your main method code will also be changed, as static methods are access using the class not instance of it:
class Program
{
static void Main(string[] args)
{
Metodo m1 = Metodos .Method1;
Metodo m2 = Metodos .Method2;
Metodo m3 = NomeMetodo;
}
}

Related

Static field problem (error CS0120) in c# [duplicate]

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!

How to access instance member in static method [duplicate]

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.

How to access class member from lambda in C#? [duplicate]

This question already has answers here:
A field initializer cannot reference the nonstatic field, method, or property - while creating a list
(2 answers)
Error 1 A field initializer cannot reference the non-static field, method, or property
(2 answers)
Closed 4 years ago.
In java I can do this
public class HelloWorld
{
public static void main(String[] args)
{
OtherClass oc = new OtherClass();
oc.a.run();
}
}
public class OtherClass
{
public int s = 3;
public Runnable a = () -> System.out.println("s is " + s);
}
The output will be s is 3. When I try this in C# with this code
using System;
namespace SomeNamespace
{
public class Program
{
public static void Main(string[] args)
{
MyClass m = new MyClass();
m.a.Invoke();
}
}
public class MyClass
{
public int s = 3;
public Action a = () => Console.WriteLine(s);
}
}
Then I get (23:51) A field initializer cannot reference the non-static field, method, or property 'SomeNamespace.MyClass.s'

How to pass two function to another function with a delegate for parameters in C#

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

while overidding base methods, why default arguments are not working well? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# optional parameters on overridden methods
using System;
namespace Apple
{
class A
{
public virtual void Func(int a=4){
Console.WriteLine(" A Class: "+a);
}
}
class B : A
{
public override void Func(int a = 12)
{
Console.WriteLine(" B Class: "+ a);
}
}
public class Program
{
static void Main(string[] args)
{
A ob = new B();
ob.Func();
Console.ReadLine();
}
}
}
// Output: B Class: 4
Default parameters are filled at compile time, and the code references a variable ob through the base class. The virtual method override works at run time, as expected. You could achieve the desired effect by using method overload:
class A
{
public void Func(int value)
{
}
public virtual void Func()
{
Func(4);
}
}
class B: A
{
public override void Func()
{
Func(12);
}
}
The compiler places the the default parameter value based on the type of the object and is done during the compile time.
Hence the compiled code would look like:
using System;
namespace Apple
{
public class Program
{
private static void Main(string[] args)
{
A ob = new B();
ob.Func(4);
Console.ReadLine();
}
}
}
You could get the desired result by doing this:
public class Program
{
static void Main(string[] args)
{
A ob = new B();
((B)ob).Func();
Console.ReadLine();
}
}
Because you creating instance of Class A which is referring to the address of class B.
A ob = new B();
Since the instance is of class A, the method you calling is pointing to method in class A.
You can check this by putting debug and then execute the code.
instead if you create instance of class B ie
B ob = new B();
it will call the method Fun() from class B and will display output as
" B Class: 12"
the default parameter value is Static binding.

Categories