A field initializer cannot reference the nonstatic field using delegates - c#

Iam very new to C#. I am learning more about delegates. When I run this code, I get the following error:
A field initializer cannot reference the nonstatic field at the line:
CalArepointer cpointer = CalculateArea;
Here is my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculatearea
{
class Program
{
delegate double CalArepointer(int r);
CalArepointer cpointer = CalculateArea;
static void Main(string[] args)
{
double area = cpointer.Invoke(20);
Console.ReadKey();
}
double CalculateArea(int r)
{
return 3.14 * r * r;
}
}
}

You should initialize the value of cpointer inside the static context of Main method since there you are going to use it:
class Program
{
delegate double CalArepointer(int r);
CalArepointer cpointer;
static void Main(string[] args)
{
cpointer = CalculateArea;
double area = cpointer.Invoke(20);
Console.ReadKey();
}
double CalculateArea(int r)
{
return 3.14 * r * r;
}
}

for the pure sake of initializing the value of cpointer outside of the main method, you want to use Static members
class Program
{
delegate double CalArepointer(int r);
static CalArepointer cpointer = CalculateArea;
static double CalculateArea(int r)
{
return 3.14 * r * r;
}
static void Main(string[] args)
{
double area = cpointer.Invoke(20);
Console.WriteLine(area);
Console.ReadKey();
}
}

Related

Creating List from JSON response [duplicate]

I have two classes, one for defining the algorithm parameters and another to implement the algorithm:
Class 1 (algorithm parameters):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public static class AlgorithmParameters
{
public static int pop_size = 100;
public static double crossover_rate = 0.7;
public static double mutation_rate = 0.001;
public static int chromo_length = 300;
public static int gene_length = 4;
public static int max_allowable_generations = 400;
static Random rand = new Random();
public static double random_num = rand.NextDouble();
}
}
Class 2 (implement algorithm):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public class Program
{
public struct chromo_typ
{
public string bits;
public float fitness;
//public chromo_typ(){
// bits = "";
// fitness = 0.0f;
//}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
public static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng =
new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
public string GetRandomBits()
{
string bits="";
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
{
if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
public static void Main(string[] args)
{
Random rnd = new Random(GetRandomSeed());
while (true)
{
chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
double Target;
Console.WriteLine("\n Input a target number");
Target = Convert.ToDouble(Console.ReadLine());
for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
{
Population[i].bits = GetRandomBits();
Population[i].fitness = 0.0f;
}
}
}
}
}
I am getting an error on Population[i].bits = GetRandomBits(); in Main().
Error is:
An object reference is required for the non-static field, method, or property 'VM_Placement.Program.GetRandomBits()'
Am I missing anything?
The Main method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits() static.
It looks like you want:
public static string GetRandomBits()
Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.
The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits() method static as well.

"An object reference is required for the non-static field, method, or property" exception when adding event handler [duplicate]

I have two classes, one for defining the algorithm parameters and another to implement the algorithm:
Class 1 (algorithm parameters):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public static class AlgorithmParameters
{
public static int pop_size = 100;
public static double crossover_rate = 0.7;
public static double mutation_rate = 0.001;
public static int chromo_length = 300;
public static int gene_length = 4;
public static int max_allowable_generations = 400;
static Random rand = new Random();
public static double random_num = rand.NextDouble();
}
}
Class 2 (implement algorithm):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public class Program
{
public struct chromo_typ
{
public string bits;
public float fitness;
//public chromo_typ(){
// bits = "";
// fitness = 0.0f;
//}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
public static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng =
new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
public string GetRandomBits()
{
string bits="";
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
{
if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
public static void Main(string[] args)
{
Random rnd = new Random(GetRandomSeed());
while (true)
{
chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
double Target;
Console.WriteLine("\n Input a target number");
Target = Convert.ToDouble(Console.ReadLine());
for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
{
Population[i].bits = GetRandomBits();
Population[i].fitness = 0.0f;
}
}
}
}
}
I am getting an error on Population[i].bits = GetRandomBits(); in Main().
Error is:
An object reference is required for the non-static field, method, or property 'VM_Placement.Program.GetRandomBits()'
Am I missing anything?
The Main method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits() static.
It looks like you want:
public static string GetRandomBits()
Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.
The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits() method static as well.

Calling class method from another class method

From my main code I'm calling a method of a class meth2 which calls another method from another class meth1. It is important for me to respect this structure.
These methods make an assignment of values that are previously defined in the classes but I am not able to get a proper result in my command window (just a 0 instead of a 132). I assume I'm missing something.
Does anybody has an idea? Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace workingWithClasses
{
class meth1
{
public int op1;
public int multiply(int mult)
{
return op1 = 44 * mult;
}
}
class meth2
{
public int CallFuncsClass(int multiplicator)
{
return m1.multiply(int multiplicator);
}
}
class Program
{
static void Main(string[] args)
{
meth1 m1 = new meth1();
meth2 m2 = new meth2();
m2.CallFuncsClass(3);
int result_m1 = m1.op1;
Console.WriteLine(opm1);
Console.ReadKey();
}
}
}
Thanks a lot!
namespace workingWithClasses
{
public class meth1
{
public int op1;
public int multiply(int mult)
{
return op1 = 44 * mult;
}
}
public class meth2
{
meth1 m1 = new meth1();
public int CallFuncsClass(int multiplicator)
{
return m1.multiply( multiplicator);
}
}
class Program
{
static void Main(string[] args)
{
meth2 m2 = new meth2();
int result_m2 = m2.CallFuncsClass(3);
Console.WriteLine(result_m2);
Console.ReadKey();
}
}
}
This code won't compile, right? This line return m1.multiply(int multiplicator); is out of the place. You need to define what is m1. I guess you are looking for dependency injection. You can do this via constructor, so
class meth2
{
private meth1 _m1;
meth2(meth1 m1)
{
if(m1 == null) throw new ... // check input params
_m1 = m1;
}
public int CallFuncsClass(int multiplicator)
{
return _m1.multiply(int multiplicator);
}
}
The usage will be
meth1 m1 = new meth1();
meth2 m2 = new meth2(m1);
m2.CallFuncsClass(3);
Bonus points
Name your classes correctly, instead of meth1 it should be something like Calculator
Don't use public fields: public int op1;. It should be private
Usually you would want your classes to be public, by default the class is internal. In this way you can use it outside a single library
Check parameters for correct value, throw exception if something is incorrect
Make multiply static on class meth1:
public static int multiply(int mult)
Also don't use 'op1', just return the result of the operation.
Call like this:
return meth1.multiply(int multiplicator);
Here is the solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace workingWithClasses
{
class meth1
{
public int op1;
public int multiply(int mult)
{
return op1 = 44 * mult;
}
}
class meth2
{
public int CallFuncsClass(int multiplicator)
{
meth1 m1=new meth1();
return m1.multiply(multiplicator);
}
}
class Program
{
static void Main(string[] args)
{
meth2 m2 = new meth2();
int result_m1=m2.CallFuncsClass(3);
Console.WriteLine(result_m1);
Console.ReadKey();
}
}
}
If you want to call methods from meth1 from within meth2 like that (without creating an object of type meth1) you need to make multiply() static.
This will allow it to be used in the manner you're using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace workingWithClasses
{
class meth1
{
//note statics
static int op1;
static int multiply(int mult)
{
return op1 = 44 * mult;
}
}
class meth2
{
public int CallFuncsClass(int multiplicator)
{
//access to multiply() is valid here
return meth1.multiply(multiplicator);
}
}
class Program
{
static void Main(string[] args)
{
meth1 m1 = new meth1();
meth2 m2 = new meth2();
m2.CallFuncsClass(3);
int result_m1 = m1.op1;
Console.WriteLine(opm1);
Console.ReadKey();
}
}
}

Getting data from the user via the command line

I want to have someone input a value for length and width in my code, here is what I got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Rectangle
{
double length;
double width;
double a;
static double Main(string[] args)
{
length = Console.Read();
width = Console.Read();
}
public void Acceptdetails()
{
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
public void Main()
{
Rectangle r = new Rectangle();
r.Display();
Console.ReadLine();
}
}
}
Is trying to use two Main methods the wrong way to approach this? This is code I was copying from http://www.tutorialspoint.com/csharp/csharp_basic_syntax.htm I'm trying to modify it around to just to get more experience with this programming language.
There are some problem with you code, let's analyse them:
a program must have a unique entry point and it must be a declared as static void, here you have two main but they are wrong
you in your static Main the one in the rectangle class you can't reference the variables length e width because they're not declared as static
console.Read() return an int that represent a character so using if the user inputs 1 you may have a different value in your length variable
your static double Main doesn't return a double
I think that what you want is:
declare the static double Main as void Main()
declare your void Main as static void Main(string[] args)
in your new static void Main call (after you create the rectangle) it's Main method (to do that you have to define it as public)
use ReadLine instead of Read()
ReadLine return a string so to transform that in a double you have to use lenght = double.Parse(Console.ReadLine())
finally call your r.display()
This is a working code that do what you want.
Note before copy pasting, since you're trying and lear read the steps and try to fix it without looking at the code
class Rectangle
{
double length;
double width;
double a;
public void GetValues()
{
length = double.Parse(Console.ReadLine());
width = double.Parse(Console.ReadLine());
}
public void Acceptdetails()
{
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
public static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.GetValues();
r.Display();
Console.ReadLine();
}
}
In this cases you'll have to tell the compiles wich is the class with the entry point.
"If your compilation includes more than one type with a Main method, you can specify which type contains the Main method that you want to use as the entry point into the program."
http://msdn.microsoft.com/en-us/library/x3eht538.aspx
And yes, having two main methods is confusing and senseless.

C# error: "An object reference is required for the non-static field, method, or property"

I have two classes, one for defining the algorithm parameters and another to implement the algorithm:
Class 1 (algorithm parameters):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public static class AlgorithmParameters
{
public static int pop_size = 100;
public static double crossover_rate = 0.7;
public static double mutation_rate = 0.001;
public static int chromo_length = 300;
public static int gene_length = 4;
public static int max_allowable_generations = 400;
static Random rand = new Random();
public static double random_num = rand.NextDouble();
}
}
Class 2 (implement algorithm):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VM_Placement
{
public class Program
{
public struct chromo_typ
{
public string bits;
public float fitness;
//public chromo_typ(){
// bits = "";
// fitness = 0.0f;
//}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
public static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng =
new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
public string GetRandomBits()
{
string bits="";
for (int i = 0; i < VM_Placement.AlgorithmParameters.chromo_length; i++)
{
if (VM_Placement.AlgorithmParameters.random_num > 0.5f)
bits += "1";
else
bits += "0";
}
return bits;
}
public static void Main(string[] args)
{
Random rnd = new Random(GetRandomSeed());
while (true)
{
chromo_typ[] Population = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];
double Target;
Console.WriteLine("\n Input a target number");
Target = Convert.ToDouble(Console.ReadLine());
for (int i = 0; i < VM_Placement.AlgorithmParameters.pop_size; i++)
{
Population[i].bits = GetRandomBits();
Population[i].fitness = 0.0f;
}
}
}
}
}
I am getting an error on Population[i].bits = GetRandomBits(); in Main().
Error is:
An object reference is required for the non-static field, method, or property 'VM_Placement.Program.GetRandomBits()'
Am I missing anything?
The Main method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits() static.
It looks like you want:
public static string GetRandomBits()
Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.
The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits() method static as well.

Categories

Resources