Float enum and aggregate class - c#

I have to create walet class, where i count how many coins it has, so:
enum Coins {
OneCent = 0.01f,
FiveCent = 0.05f,
OneDollar = 1.0f
}
and:
public class RowQuantity<T> {
public T entity;
public int Quantity;
}
and my walet:
public class Walet {
public List<RowQuantity<Coins>> CoinsCash;
public Walet() {
this.CoinsCash.Add(new RowQuantity<Coins> { entity = Coins.OneCent, Quantity = 25 });
}
}
The problem goes here:
I can't have enum with float value => so, i have to declare it as a static class.
public static class Coins {
public const float OneCent = 0.01f;
public const float FiveCent = 0.05f;
public const float OneDollar = 1.0f;
}
But in this way, i can't pass static type as instance of generic class.
So, how could i realise this? (List with quantity of float enum values)

First of all, to avoid rounding issues, you need to use decimal. Secondly, you need to make it an instance class that shows some static properties that are OneCent, FiveCent and OneDollar, like so:
public sealed class Coins
{
private decimal _num;
private Coins(decimal num)
{
_num = num;
}
public static readonly Coins OneCent = new Coins(0.01M);
public static readonly Coins FiveCent = new Coins(0.05M);
public static readonly Coins OneDollar = new Coins(1M);
//add more properties like this
}

Related

I've multiple classes which differs only a bit. Is there a better approach?

still learning my way thorugh unity and c# i got the following problem.
Ive multiple classes which differs only a bit. Iam faceing now the problem that ive some methods which only needs the ID value of the class and name for my buildingsystem but i cant pass the list over as the list passed is always from a different type of object. Is there a better approach for this
Here the 2 sample classes + the function i want to pass the list later on to get just the ID + Name value of the class.
Class Electricty:
public class Electricity
{
public int electricityID;
public string electricityName;
public float electricityPower;
public double electricityCost;
public Sprite electricitySprite;
public bool isPlaced;
public Vector3 electricityPosition;
public Electricity(int id, string name, float power, double cost, Sprite sprite, bool placed, Vector3 position)
{
this.electricityID = id;
this.electricityName = name;
this.electricityPower = power;
this.electricityCost = cost;
this.electricitySprite = sprite;
this.isPlaced = placed;
this.electricityPosition = position;
Debug.Log("New Electricity created");
}
Class Security:
public class Security
{
public int securityID;
public string securityName;
public double securityCost;
public Sprite securitySprite;
public Security(int id, string name, double cost, Sprite sprite)
{
this.securityID = id;
this.securityName = name;
this.securityCost = cost;
this.securitySprite = sprite;
Debug.Log("New Security created");
}
}
Function ive where the class List later will be passed to
public void StartBuildingSystem(List<Electricty> electricityList, int count, string name)
{
uiPhone.SetActive(false);
uiPlacement.SetActive(true);
PlacingAreas(GetActiveBluePrint(name), GetActiveType(electricityList, name));
activeBuildingType = GetActiveBuildingType(name);
//uiPlacement.SetActive(false);
}
public void StartBuildingSystem(List<Security> securityList, int count, string name)
{
uiPhone.SetActive(false);
uiPlacement.SetActive(true);
PlacingAreas(GetActiveBluePrint(name), GetActiveType(securityListList, name));
activeBuildingType = GetActiveBuildingType(name);
//uiPlacement.SetActive(false);
}
Could anyone give me any idea what would be a better approach so i dont have to make multiple functions which does except same just get a different list passed over.
Thank you.
The easiest thing would probably we a Parent Class from which both of your classes inherit.
Parent Class:
// System Base Class
public class System {
// Member Variables.
[SerializeField]
private int id;
[SerializeField]
private string name;
[SerializeField]
private double cost;
[SerializeField]
private Sprite sprite;
// Constructor.
public Security(int id, string name, double cost, Sprite sprite) {
// Set Member Variables.
this.id = id;
this.name = name;
this.cost = cost;
this.sprite = sprite;
Debug.Log("New System created");
}
}
After you've created that Parent Class you can inherit from it and then set the values in your Child Class.
Electricity Child Class:
public class Electricity : System {
// Member Variables.
[SerializeField]
private bool isPlaced;
[SerializeField]
private Vector3 position;
// Constructor.
public Electricity(int id, string name, float power, double cost,
Sprite sprite, bool placed, Vector3 position) {
// Set Member Variables.
this.id = id;
this.name = name;
this.power = power;
this.cost = cost;
this.sprite = sprite;
this.isPlaced = placed;
this.position = position;
Debug.Log("New Electricity created");
}
}
Additionally you can use use the function for both Child Classes. If you use Generic Methods (T).
public void StartBuildingSystem(List<T> list, int count, string name) {
uiPhone.SetActive(false);
uiPlacement.SetActive(true);
PlacingAreas(GetActiveBluePrint(name), GetActiveType(list, name));
activeBuildingType = GetActiveBuildingType(name);
//uiPlacement.SetActive(false);
}

Access constructor value

I am trying to access value in my code. I have two classes, carex and engine.
The engine class has the following code:
public class Engine
{
public string Size;
public int HorsePower;
public float FuelConsumtionRate;
public Engine()
{
}
public Engine(string cylinder, int hp, float fuelRate)
{
Size = cylinder;
Console.WriteLine($"Engine type: {cylinder}");
HorsePower = hp;
Console.WriteLine($"Horse power: {hp} hp");
FuelConsumtionRate = fuelRate;
Console.WriteLine($"Fuel consumption: {fuelRate} l/h");
}
}
The carex class has the following code:
public class CarEx
{
string Manfacturer;
string RegistrationNr;
float Fuel;
float Speed;
bool IsRunning;
public CarEx(string manuf, float fuel, string regNr)
{
Manfacturer = manuf;
this.Fuel = fuel;
RegistrationNr = regNr;
Console.WriteLine("_____________________________________________________");
Console.WriteLine($"Manufacturer; {manuf}, Fuel amount: {fuel}l, License: {regNr}");
Console.WriteLine("______________________________________________________");
}
public void ChooseEngineType()
{
Engine v4 = new Engine("v4", 200, 0.7f);
}
public void FillFuel(float amount)
{
Fuel += amount;
/*
Fuel -= 0.7f;
*/
}
public static void RunCar()
{
CarEx car1 = new CarEx("Saab", 10, "1234DD");
car1.CallCustomer();
Console.WriteLine($"Maker: {car1.Manfacturer}");
Console.WriteLine($"Registration nr: {car1.RegistrationNr}");
}
}
I would like to replace the hard coded fuel consumption rate
Fuel -= 0.7f;
which I commented out with the value set in the engine constructor so its not hard coded any more.
What am I missing out on?
Your ChooseEngineType method creates an Engine object, but it is stored in a local variable which ceases to exist as soon as the method ends.
Change that variable to a field or property Engine engine at class level, and then you can use engine and its property engine.FuelConsumtionRate in all methods.
(PS, the proper spelling of that property would be FuelConsumptionRate)
Assuming that the fuel consumption rate is constant, you can use a constant that is privately accessible in the class you've declared by doing this:
private const float fuelConsumptionRate = 0.7f;
and then use it in your code so that you do not hard-code the changes. Otherwise, if the rate is bound to change, you'll need to store either the Engine itself (most recommended), or just the consumption rate in a private field like this:
private Engine engine;
// or
private float fuelConsumptionRate;
// the rest of your class' code
public void ChooseEngineType()
{
float rate = 0.7f;
Engine v4 = new Engine("v4", 200, rate);
engine = v4;
// or
fuelConsumptionRate = rate;
}
Added a new constructor for fuel rate in Engine class
public class Engine
{
public static string Size;
public static int HorsePower;
public static float FuelConsumtionRate;
//Constructor to set fuel reate
public Engine(float fuelRate)
{
FuelConsumtionRate = fuelRate;
}
public Engine(string cylinder, int hp, float fuelRate)
{
Size = cylinder;
Console.WriteLine($"Engine type: {cylinder}");
HorsePower = hp;
Console.WriteLine($"Horse power: {hp} hp");
FuelConsumtionRate = fuelRate;
Console.WriteLine($"Fuel consumption: {fuelRate} l/h");
}
And in the carex class:
public class CarEx
{
string Manfacturer { get; set; }
string RegistrationNr { get; set; }
float Fuel;
float Speed;
bool IsRunning;
public CarEx(string manuf, float fuel, string regNr)
{
Manfacturer = manuf;
this.Fuel = fuel;
RegistrationNr = regNr;
Console.WriteLine("_____________________________________________________");
Console.WriteLine($"Manufacturer; {manuf}, Fuel amount: {fuel}l, License: {regNr}");
Console.WriteLine("______________________________________________________");
}
public void ChooseEngineType()
{
Engine v4 = new Engine("v4", 200, 0.7f);
}
public void Accelerate()
{
Speed += 6.0f;
//Fuel rate set for v4 object
Fuel -= Engine.FuelConsumtionRate;
}

C# Access Struct using String

I am a bit stuck with my game. I have a class called Upgradebuttons. From this class I want to access some variables stored in a struct from another class. I can easily access the variables by typing classname.structname.preferedvar but the structname depends on which upgrade as been clicked. So I want to call the struct using a string. I have tried:
MethodInfo method = typeof(Classname).GetMethod(structname);
But this only works if it is a void and not a struct. What do I need to do in order to get this working?
public class UpgradeButtons : MonoBehaviour {
public void somefunction{
// here i want to have access
}
}
This is an example of the class I want to have access to:
public class Upgrades: MonoBehaviour {
public struct Upgrade1{
public const int Cost = 10;
public const float Value = 0.1f;
public static string Naam = "Autoclicker";
}
}
While this is possible, it sounds like poorly thought out design. Perhaps you could use one common struct Upgrade and use the Name property to find it at runtime?
Example:
public struct Upgrade
{
public string Name;
public int Cost;
public float Value;
public Upgrade(string name, int cost, float value)
{
this.Name = name;
this.Cost = cost;
this.Value = value;
}
}
public class UpgradeButtons : MonoBehavior
{
List<Upgrade> Upgrades = new List<Upgrade>();
public void CreateButtons()
{
Upgrades.Add(new Upgrade("Autoclicker", 10, 0.1f));
//etc...
}
public void somefunction()
{
Upgrade autoclickUpgrade = Upgrades.Where(p => p.Name == "Autoclicker").FirstOrDefault();
if(autoclickUpgrade == null)
throw new Exception("Could not find Autoclicker upgrade.");
//do something with autoclickUpgrade
}
}
just remove static from string Naam:
public class Upgrades: MonoBehaviour {
public struct Upgrade1{
public const int Cost = 10;
public const float Value = 0.1f;
public string Naam = "Autoclicker";
}
}
When an object ( class, variable, method) is defined as static it can not be referenced through an instance.
If I understand your question, you are on the right track, probably. Since the struct (type) that your add-on depends on may or may not exist, Reflection is the best way to go here.
Try Assembly.GetType(), or a related method, to attempt to load the type, check its existence, and iterate its members.
http://msdn.microsoft.com/en-us/library/y0cd10tb(v=vs.110).aspx

Can a class return a static instance of itself? (in c#)

Right now my class is set up as:
enum Unit{Inches,Centimeters};
Later on I have a step that sets all of the properties of each of these units into my classes instance variables. For example:
int unitBase; //10 for metric, 16 for american
int label;
switch(unit)
{
case Unit.Inches: unitBase = 16; unitLabel = "\"";break;
case Unit.Centimeters: unitBase = 10; unitLabel = "cm";break;
}
I would rather store this all in a Unit class or struct. Then, I would like to be able to access it in the same way you access colors, for example. You say Color.Blue for a blue color, I would like to say Unit.Inches for inches... That is why I dont make a unit base class and simply extend it.
I know that there is a way to do this! Could anyone enlighten me?
Thanks!
You can use static properties:
public enum UnitSpecifier{Inches,Centimeters};
public class Unit
{
int unitBase; //10 for metric, 16 for american
string unitLabel;
public Unit(UnitSpecifier unit)
{
switch (unit)
{
case UnitSpecifier.Inches: unitBase = 16; unitLabel = #"\"; break;
case UnitSpecifier.Centimeters: unitBase = 10; unitLabel = "cm"; break;
}
}
public static readonly Unit Inches = new Unit(UnitSpecifier.Inches);
}
public struct Unit {
public static readonly Unit Inches = new Unit(16, "\"");
public static readonly Unit Centimeters = new Unit(10, "cm");
private readonly int _unitBase;
private readonly string _unitLabel;
static Unit() { }
private Unit(int unitBase, string unitLabel) {
this._unitBase = unitBase;
this._unitLabel = unitLabel;
}
public int UnitBase {
get { return this._unitBase; }
}
public string UnitLabel {
get { return this._unitLabel; }
}
}

member variable not an option

I have many constants I need to move around in one of my classes but I'm not allowed to use member variables. What are some options?
Here's my initial try:
private void MyConstants(out int textSize, out int paddingValue, out int borderType, ...)
{
//Set them here
}
private Method1()
{
int textSize = 0;
int paddingValue = 0;
int borderValue = 0;
....
MyConstants(out textSize, out paddingValue, out borderValue)
}
private Method2()
{
int textSize = 0;
int paddingValue = 0;
int borderValue = 0;
....
MyConstants(out textSize, out paddingValue, out borderValue)
}
//Many more methods...Just seems to repetitive.
Use Private Class or Struct.
private class Variables {
public int textSize;
public int paddingValue;
public int borderValue;
}
private Variables MyConstants{
get{ return new Variables(){textSize=1, paddingValue=2, borderValue=3};}
}
If you need to initialize in constructor try using readonly instead on const.
Edit 1:
You can create a class that holds a private Dictionary:like key and value.
put a "object LoadConstant(string)" method in it that will withdraw the data.
public static class ConstantManager {
private static Hashtable _consts = new Hashtable();
private static const keyName = "Name 1";
public static void ConstantManager()
{
_consts[keyName] = ...;
}
public static Hashtable GetConstants()
{
var _copy = new Hashtable(_consts);
return _copy;
}
}
public OtherClass{
public void Method()
{
var consts = ConstantManager.GetConstants();
var a = consts[ConstantManager.keyName];
}
}

Categories

Resources