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!
Related
This question already has answers here:
How to implement a read only property
(8 answers)
What is the difference between const and readonly in C#?
(30 answers)
Closed 1 year ago.
I want to declare a variable in my class, that cannot be changed later like this:
obj myobj=new obj()
myobj.CONSTANT_VAR="Changed value" //ERROR!!
...but whose value can be accessed like:
Console.WriteLine(myobj.CONSTANT_VAR)
I tried the following:
public class obj{
public int a, b;
public const string CONSTANT_VAR;
public obj(int x,int y){
a=x;
b=y;
CONSTANT_VAR=1/(a*((""+a).Length)+3/(b*((""+b).Length)).ToString();
}
public int do(){
return this.a+this.b-(CONSTANT_VAR).Length;
}
}
class DriverClass(){
static void Main(){
obj myObj=new obj(2,3);
myObj.a=34;
myObj.b=35;
myObj.CONSTANT_VAR="changed ur string lol"; //i want it to print error
Console.WriteLine(CONSTANT_VAR); //no error
Console.WriteLine(myObj.add());
}
}
But i instead get the following error message:
constants must have a value assigned
But i dont want to assign it a value beforehand.....
What do i do?
You're looking for read-only fields or properties, not const which is for genuine global constants.
I'd recommend avoiding public fields entirely, and instead using properties - so in this case you'd want a get-only property. Following .NET naming conventions, you'd have something like:
public class Obj
{
public int A { get; set; }
public int B { get; set; }
public string ConstantVar { get; }
public Obj(int x, int y)
{
A = x;
B = y;
ConstantVar = /* complex expression */
}
public int Do() => A + B - ConstantVar.Length;
}
You can use Readonly, it gives you option to set the value once and can not be changed later.
public class obj(){
public int a, b;
public readonly string CONSTANT_VAR;
public obj(int x,int y){
a=x;
b=y;
CONSTANT_VAR=1/(a*((""+a).Length)+3/(b*((""+b).Length)).ToString();
}
public int do(){
return this.a+this.b-(CONSTANT_VAR).Length;
}
}
class DriverClass(){
static void Main(){
obj myObj=new obj(2,3);
myObj.a=34;
myObj.b=35;
myObj.CONSTANT_VAR="changed ur string lol"; //i want it to print error
Console.WriteLine(CONSTANT_VAR); //no error
Console.WriteLine(myObj.add());
}
}
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.
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'
Okay, so what I'm trying to do here is create an array of classes. My class TEAMLEADER is derived from an abstract class, Employee. However when I try to create an instance of TEAMLEADER in Main, I get an error message saying TEAMLEADER cannot be found.
namespace Lab3
{
public abstract class Employee
{
protected string EmployeeName;
protected int EmployeeNumber;
protected double WeeklySalary;
public Employee (string EmployeeName, int EmployeeNumber, double WeeklySalary)
{
this.EmployeeName = EmployeeName;
this.EmployeeNumber = EmployeeNumber;
this.WeeklySalary = WeeklySalary;
}
public Employee(string EmployeeName)
{
assignID(EmployeeNumber);
}
public override string ToString()
{
return EmployeeName + " " + EmployeeNumber + " " + WeeklySalary;
}
protected virtual double CalcSalary()
{
return CalcSalary();
}//"Virtual" is a keyword that says, "This can be overriden in the derived class."
private static int assignID(int EmployeeNumber)
{
EmployeeNumber.ToString();
EmployeeNumber++;
return EmployeeNumber;
}
}
class Program
{
static void Main(string[] args)
{
Employee[] workerarray = new Employee[4];
workerarray[0] = new TeamLeader("Rachel", 18, 1000000.00, 52000000.00, true);
}
}
}
In a separate class/tab is the TEAMLEADER class.
public class TeamLeader:Employee
{
protected double AnnualSalary;
protected bool WeeklyGoal;
public override void CalcSalary()
{
if (WeeklyGoal == true)
{ CalcSalary = (AnnualSalary / 52) * 1.10; }
else (CalcSalary = AnnualSalary / 52);
}
public TeamLeader(string EmployeeName, int EmployeeNumber, double WeeklySalary, double AnnualSalary, bool WeeklyGoal):base(EmployeeName, EmployeeNumber, WeeklySalary)
{
this.WeeklyGoal = WeeklyGoal;
this.AnnualSalary = AnnualSalary;
}
}
The problem is in my main method. I can't understand why I can't create an instance of TeamLeader. It's not an abstract class, so shouldn't Main be able to recognize it and create an instance?
Have you tried adding:
using Lab3;
to the top of your Main class file?
Try this
Make sure you added namespace Lab3 to the top of your file where TeamLeader class is located. Then add this line of code using Lab3; to the top of your main file.
If that does not work for you try this.
Maby you added TeamLeader class to a different assembly
To solve this.
Click on References in the assembly where your main is located
Click on Add Reference
Click on Projects > Solutions and add your assembly
Please let me know if it worked or not
Do you have a public default constructor in your class?
public Employ()
{
}
When the command
Employee[] workerarray = new Employee[4];
is executed, it needs to create 4 new objects of type Employ, but those cannot be created because there is not a parameter-less constructor.
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.