Calling class method from another class method - c#

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

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.

Namespace error while defining a BitVector32 collection in C#

I have written the following code in visual studio 2019, but it gives me an error saying that BitVector32 is a namespace but is used as a type here and CreateMask() method is not existing in the BitVector32 namespace
using System;
using System.Collections.Specialized;
namespace BitVector32
{
class Program
{
static void Main(string[] args)
{
basicVector();
}
public static void basicVector()
{
BitVector32 b = new BitVector32(0);
int myBit1 = BitVector32.CreateMask();
int myBit2 = BitVector32.CreateMask(myBit1);
int myBit3 = BitVector32.CreateMask(myBit2);
int myBit4 = BitVector32.CreateMask(myBit3);
int myBit5 = BitVector32.CreateMask(myBit4);
}
}
}
i referred the Microsoft doc at https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.bitvector32?view=netcore-3.1 and did the same but it gives the above mentioned errors
This is due to your namespace at the top being BitVector32. Change the namespace to another name other than BitVector32:
using System;
using System.Collections.Specialized;
namespace SomethingOtherThanBitVector32
{
class Program
{
static void Main(string[] args)
{
basicVeector();
}
public static void basicVeector()
{
BitVector32 b = new BitVector32(0);
int myBit1 = BitVector32.CreateMask();
int myBit2 = BitVector32.CreateMask(myBit1);
int myBit3 = BitVector32.CreateMask(myBit2);
int myBit4 = BitVector32.CreateMask(myBit3);
int myBit5 = BitVector32.CreateMask(myBit4);
}
}
}

"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.

Creating a Random number(in Class) for later extensive use in program C#

I have to create a program where the player has 6 choices, between 2 pets, he must decide either to feed, talk or play with each one, however he can only do one at a time and each time he chooses an option the option chosen (except when talking) makes the other options increase while the former one decreases.
Im having trouble in all aspects, inside the program and inside the class.
I can't seem to define the random numbers inside the Class, and that makes the program not work.
This is the code for the Class so far, here is where the problem must be happening:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tamagochi
{
class Tamagochi
{
private string tamagochi;
private double hungerLvl;
private double boredomLvl;
private double totalLevels;
private static int time;
private static int RandomNumberGenerator;
private static int ranNum1;
private static int ranNum2;
private static int ranNum3;
private static int ranNum4;
public Tamagochi (string tamagochi)
{
this.tamagochi = tamagochi;
}
public Tamagochi (string tamagochi, double hungerLvl, double boredomLvl, double randomNumbers, int RandomNumberGenerator)
{
this.tamagochi = tamagochi;
this.hungerLvl = hungerLvl;
this.boredomLvl = boredomLvl;
this.RandomNumberGenerator = RandomNumberGenerator;
}
public static void IncreaseTime()
{
++time;
}
public static void IncreaseBoredomLvl(double boredomLvl, int random)
{
boredomLvl += // randomnumber
}
public static void IncreaseHungerLvl(double hungerLvl)
{
hungerLvl += //randomnumber
}
public static void randomNumber(int min, int max)
{
Random RandomNumberGenerator = new Random();
ranNum1 = RandomNumberGenerator.Next(1, 6);
ranNum2 = RandomNumberGenerator.Next(1, 6);
ranNum3 = RandomNumberGenerator.Next(1, 6);
ranNum4 = RandomNumberGenerator.Next(1, 6);
}
//return section
public string GetTamagochi()
{
return tamagochi;
}
public double GetBoredomLvl()
{
return boredomLvl;
}
public double GetHungerLvl()
{
return hungerLvl;
}
public static int GetTime()
{
return time;
}
public static int GetRandomNum()
{
return ranNum1;
}
}
}
Any help on trying to make this work?
The Random number should be declared outside the function.
The seed should be effective.
If you want a number between 1 and 6 (both including) you should put in the Next() function from 1 to 7 (because 7 is not included)
So, Your code should look like this:
class Tamagochi
{
private int ranNum1;
private int ranNum2;
private int ranNum3;
private int ranNum4;
Random RandomNumberGenerator;
public Tamagochi()
{
RandomNumberGenerator = new Random(Guid.NewGuid().GetHashCode());
}
public void GetRandomNumber()
{
ranNum1 = RandomNumberGenerator.Next(1,7);
ranNum2 = RandomNumberGenerator.Next(1,7);
ranNum3 = RandomNumberGenerator.Next(1,7);
ranNum4 = RandomNumberGenerator.Next(1,7);
}
}

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