Unity/C# one function to set any int? - c#

I've got a small project where I would like to avoid creating a setter for each integer.
So I'm thinking if it's even possible.
So I would like to set an amount of
player.setResource(player.money, 100);,
player.setResource(player.coal, 20);,
etc.
I'm not sure first of all if it's possible, and second of all how to write a function itself.
public void setResource(int resource, int amount)
{
???
}

Use an enum for this. Define an enum in your project like so
public enum ResourceType { Coal = 0, Money = 1, Health = 2 }
Now, you can add a switch case in your setResource function to check what enum you've passed, and set the corresponding value. This is however assuming all your values are integers. you can make a separate one for floats, or just use floats for everything, upto you.
This will be your new SetResource Function, assuming you have a reference to your player.
public void setResource(ResourceType resource, int amount)
{
switch(resource)
{
case ResourceType.Money:
player.money = amount;
break;
case ResourceType.Coal:
player.coal = amount;
break;
}
}

You can use an Enum to define the resources types and a Dictionary to store the values of each resource. Here's an example:
public enum ResourceType
{
Coal,
Money
}
private Dictionary<ResourceType, int> _resources = new Dictionary<ResourceType, int>();
public void SetResource(ResourceType resourceType, int value)
{
_resources[resourceType] = value;
}
public int GetResource(ResourceType resourceType, int defaultValue = 0)
{
if (_resources.TryGetValue(resourceType, out var value))
return value;
else
return defaultValue;
}

public class Player
{
public int money { get; set; }
public int coal { get; set; }
public void setResource(string resource, int amount)
{
this.GetType().GetProperty(resource).SetValue(this, amount);
}
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Player player = new Player();
player.setResource(nameof(player.coal), 4);
}
}

In your method, the target is not passed, the value of the integer is assigned to a local variable resource that only exists within the method.money and coal are not affected.
You need to pass the address of those data.
public void setResource(ref int resource, int amout)
{
resource = amount;
}
player.setResource(ref player.coal, 100);
If nothing else happens in the method, a get/set property would do the same.

There are multiple ways how you could do this.
I often use this aproach for quick prototyping.
First you create two variables for the data you want to assing, then you create a Setter function and with this you can set variables through other scripts.
int value 1;
int value 2;
public void SetData(int value1, int value2)
{
this.value1 = value1;
this.value2 = value2;
}
The same aproach can be used for other data types, you just need to create the variables.

Related

Understand function from get set method

I am using a get set method to loop another method. As shown below, I am trying to increase the value of Table10_3 in the ValuesForTableLooping class. In the Main method, I have called the get set property to increase the value by one.
I have 2 questions at hand,
Is there a way to call the get set method without putting it as Inc.Val = 0;?
Why does changing any value in Inc.Val = 0; not affect the outcome?
class Class2
{
public class ValuesForTableLooping
{
public static int Table10_3 = 1;
}
public static void Main()
{
Console.WriteLine(ValuesForTableLooping.Table10_3);
Increase Inc = new Increase();
Inc.Val = 0;
Console.WriteLine(ValuesForTableLooping.Table10_3);
Inc.Val = 0;
Console.WriteLine(ValuesForTableLooping.Table10_3);
Inc.Val = 0;
Console.WriteLine(ValuesForTableLooping.Table10_3);
}
public class Increase
{
private int val;
public int Val
{
get { return val; }
set { val = ValuesForTableLooping.Table10_3++; }
}
}
}
Thank you so much once again!
Your design is pretty strange and you seem to have a great misunderstanding on what properties are.
A property is nothing - as you noticed - as a get- and a set-method. So you could achieve the exact same with the following code:
public int get_Val() { return val; }
public void set_Val(int value) { val = ValuesForTableLooping.Table10_3++; }
And here is the weird thing. A setter expects a new value for your property, which is provided as value. However you donĀ“t use that value at all in your implementation. Instead you just increase val by one, which I would call a really strange design. You either want to set the new value from the outside with this:
public void set_Val(int value) { val = value; }
or in the property-notation:
public int Val {
get { return val; }
set { val = value; }
}
which can be further simplified by using an auto-implemented property:
public int Val { get; set; }
Another - IMHO better - way is to omit the setter completely and create some IncreaseVal-method instead:
public void IncreaseVal() { ValuesForTableLooping.Table10_3++; }
Last but not least Increase is a very bad name for a class. It does not describe a thing, but something you can do with a thing.

Passing variable from another class as input but not getting value back

I have a class where I hold some variables :
public class PreviousCalls
{
private static int bot1Call;
public static int previousBot1Call
{
get { return bot1Call; }
set { bot1Call = value; }
}
private static int bot2Call;
public static int previousBot2Call
{
get { return bot2Call; }
set { bot2Call = value; }
}
private static int bot3Call;
public static int previousBot3Call
{
get { return bot3Call; }
set { bot3Call = value; }
}
private static int bot4Call;
public static int previousBot4Call
{
get { return bot4Call; }
set { bot4Call = value; }
}
private static int bot5Call;
public static int previousBot5Call
{
get { return bot5Call; }
set { bot5Call = value; }
}
}
I need to pass those variables as parameters to a lot of methods in my other class here's how I do it :
void AI(... , int previous)
AI(... , PreviousCalls.previousBot1Call);
So the parameter previous is changing the way it should but the variables from class PreviousCalls are not changing at all, why is that ?
int is value type, so there is a copy of 'previous value' passed to method body. So changing a variable inside method doesn't cause the original value change:
public void Test(int a)
{
a = 10;
}
int t = 11;
Test(t);
//t is still 11, because Test method operates on copy of t
To change original value you must use ref or out:
void AI(..., ref int previous) { ... }
int param;
AI(..., ref param); //when ref is used, original variable wil be changed.
PreviousCalls.previousBot1Call = param;
Unfortunately, you cannot use it like this:
AI(... , ref PreviousCalls.previousBot1Call); // compile-time error
// member-access is forbidden wtih out/ref
AI(,.., ref 10); // compile-time error
Another attempt:
interface IAIParam
{
int Previous { get; set; }
// other params
}
void AI(IAIParam p)
{
p.Previous += 1;
//....
}
And then implementaiton:
internal class MyBotProxy : IAIParam
{
public int Previous
{
get { return PreviousCalls.previousBot1Call; }
set { PreviousCalls.previousBot1Call = value; }
}
}
usage:
var myProxy = new MyBotProxy();
AI(myProxy);
Most commonly methods do not change any values outside of their method scope, instead they return a new value. Only methods that accept the parameter by reference instead of value can change the value of the parameter in the calling context.
This article on MSDN is a great starting point for understanding how to pass parameters by reference instead of value.
Please note that you will not be able to pass a class member as a ref or out parameter. If you wish to update part of a class via reference, you will need to pass the entire class object as the reference.

Ensure Variable Initialization C#

Consider this code:
public string Variable1 { get; set;}
public int Variable2 { get; set;}
public void Function()
{
// Has been Variable1 Initialized?
}
Inside the function, I want to know if a value has been sent to Variable1 & Variable2, prior to the function call,
even if the DEFAULT values have been sent, that's ok (null for string & 0 for int)
Consider using a simple wrapper like this:
public struct AssignableProperty<T>
{
private T _value;
public T Value
{
get { return _value; }
set
{
WasAssigned = true;
_value = value;
}
}
public bool WasAssigned { get; private set; }
public static implicit operator AssignableProperty<T>(T data)
{
return new AssignableProperty<T>() { Value = data };
}
public static bool operator ==(AssignableProperty<T> initial, T data)
{
return initial.Value.Equals(data);
}
public static bool operator !=(AssignableProperty<T> initial, T data)
{
return !initial.Value.Equals(data);
}
public override string ToString()
{
return Value.ToString();
}
}
Then your class'll look like this:
public class Test
{
public AssignableProperty<string> Variable1 { get; set; }
public AssignableProperty<int> Variable2 { get; set; }
public void Function()
{
if(Variable1.WasAssigned&&Variable2.WasAssigned)
//do stuff
}
}
You can go further and add throw Exception or contract to getter, so if somebody'll try to access uninitialized value it'll throw an exception or show you warning
Some basics about default value in C#:
When an instance of a class (or struct) is created, all fields are initialized to their respective default value.
For reference types, it will be null. For value types, it will be equivalent to 0. This is easily explains as the memory management ensures that new allocated memory is initialized to 0x0 bytes.
Auto-properties hide the generated field, but there is one. So the same rules apply.
Now to answer your question, the best way to make sure that values are initialized is to make a constructor with one parameter for each field/property and to hide the default constructor with no parameters:
public Yourtype(String param1, Int32 param2)
{
this.Variable1 = param1;
this.Variable2 = param2;
}
private Yourtype() { }
Other alternatives is described in #Sean and #Alex answers if only a subset of properties/fields needs to be initialized/checked. But this hides some overhead (one bool for each property/field and some indirection).
For the reference types you'll need to add a flag:
string m_Variable1;
bool m_IsVariable1Set;
public string Variable1
{
get{return m_Variable1;}
set{m_IsVariable1Set = true; m_Variable1 = value;}
}
For the value types you can use a nullable value
int? m_Variable2;
int Variable2
{
get{return m_Variable2.GetValueOrDefault();}
set{m_Variable2 = value;}
}
Which you can then check to see if it's been set by using m_Variable2.HasValue.
Well you can simply do a check on both variables to see if they have any value assigned to them in your function
public void Function()
{
if (String.IsNullOrEmpty(Variable1) && Variable2 ==0 )
{
// Variables are not assigned
}
}

ASP.NET creating my own type to use in a domain object

I am busy building my Domain for a new application and I came across the situation where I need to create my own type.
I want to create a type called Frequency.
It needs to be a decimal with 3 decimal places.
Some examples:
135.000
135.100
135.001
etc
It always needs to have 3 decimal places.
I also want to put some specific bounds and validation on the object that is why I thought it would be best to create a custom type.
So my question is:
How do I go about doing this?
How do I get a decimal to always have 3 decimal places and to not go
135.1 when it should be 135.000
Attempt:
public class Frequency
{
private decimal frequency;
public void setFrequency(Frequency tmp)
{
this.frequency = tmp;
}
public Frequency getFrequency()
{
return this.frequency;
}
}
You can make use of the implicit and operator keywords to achieve this:
public class Frequency
{
private double freq;
public double Value
{
get { return freq; }
private set { freq = value; }
}
private Frequency(double value)
{
this.freq = value;
}
public static implicit operator Frequency(double value)
{
return new Frequency(value);
}
public static implicit operator double(Frequency freq)
{
return freq.Value;
}
public override string ToString()
{
return freq.ToString("0.000");
}
}
This allows you to set the value (Frequency data = 153) and also access it for mathematical operations
Frequency data = 153;
double multi = data * 153;

How do I reinitialize or reset the properties of a class?

I've created a class with properties that have default values. At some point in the object's lifetime, I'd like to "reset" the object's properties back to what they were when the object was instantiated. For example, let's say this was the class:
public class Truck {
public string Name = "Super Truck";
public int Tires = 4;
public Truck() { }
public void ResetTruck() {
// Do something here to "reset" the object
}
}
Then at some point, after the Name and Tires properties have been changed, the ResetTruck() method could be called and the properties would be reset back to "Super Truck" and 4, respectively.
What's the best way to reset the properties back to their initial hard-coded defaults?
You can have the initialization in a method instead of inlining with the declaration. Then have the constructor and reset method call the initialization method:
public class Truck {
public string Name;
public int Tires;
public Truck() {
Init();
}
public void ResetTruck() {
Init();
}
private void Init() {
Name = "Super Truck";
Tires = 4;
}
}
Another way is not to have a reset method at all. Just create a new instance.
Reflection is your friend. You could create a helper method to use Activator.CreateInstance() to set the default value of Value types and 'null' for reference types, but why bother when setting null on a PropertyInfo's SetValue will do the same.
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Length; ++i)
properties[i].SetValue(this, null); //trick that actually defaults value types too.
To extend this for your purpose, have private members:
//key - property name, value - what you want to assign
Dictionary<string, object> _propertyValues= new Dictionary<string, object>();
List<string> _ignorePropertiesToReset = new List<string>(){"foo", "bar"};
Set the values in your constructor:
public Truck() {
PropertyInfo[] properties = type.GetProperties();
//exclude properties you don't want to reset, put the rest in the dictionary
for (int i = 0; i < properties.Length; ++i){
if (!_ignorePropertiesToReset.Contains(properties[i].Name))
_propertyValues.Add(properties[i].Name, properties[i].GetValue(this));
}
}
Reset them later:
public void Reset() {
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Length; ++i){
//if dictionary has property name, use it to set the property
properties[i].SetValue(this, _propertyValues.ContainsKey(properties[i].Name) ? _propertyValues[properties[i].Name] : null);
}
}
Unless creating the object is really expensive (and Reset isn't for some reason). I see no reason to implement a special reset method. Why don't you just create a new instance with a usable default state.
What is the purpose of reusing the instance?
If you did your initialization in a Reset method you can be good to go:
public class Truck {
public string Name;
public int Tires;
public Truck() {
ResetTruck();
}
public void ResetTruck() {
Name = "Super Truck";
Tires = 4;
}
}
Focusing of separation of concerns (like Brian mentioned in the comments), another alternative would be to add a TruckProperties type (you could even add your default values to its constructor):
public class TruckProperties
{
public string Name
{
get;
set;
}
public int Tires
{
get;
set;
}
public TruckProperties()
{
this.Name = "Super Truck";
this.Tires = 4;
}
public TruckProperties(string name, int tires)
{
this.Name = name;
this.Tires = tires;
}
}
Inside your Truck class, all you would do is manage an instance of the TruckProperties type, and let it do its reset.
public class Truck
{
private TruckProperties properties = new TruckProperties();
public Truck()
{
}
public string Name
{
get
{
return this.properties.Name;
}
set
{
this.properties.Name = value;
}
}
public int Tires
{
get
{
return this.properties.Tires;
}
set
{
this.properties.Tires = value;
}
}
public void ResetTruck()
{
this.properties = new TruckProperties();
}
}
This certainly may be a lot of (unwanted) overhead for such a simple class, but in a bigger/more complex project it could be advantageous.
That's the thing about "best" practices... a lot of times, there's no silver bullet, but only recommendations you must take with skepticism and your best judgement as to what applies to you in a particular case.
I solved a similar problem with reflection. You can use source.GetType().GetProperties() to get a list of all properties which belong to the object.
Although, this is not always a complete solution. If your object implements several interfaces, you will also get all those properties with your reflection call.
So I wrote this simple function which gives us more control of which properties we are interested in resetting.
public static void ClearProperties(object source, List<Type> InterfaceList = null, Type SearchType = null)
{
// Set Interfaces[] array size accordingly. (Will be size of our passed InterfaceList, or 1 if InterfaceList is not passed.)
Type[] Interfaces = new Type[InterfaceList == null ? 1 : InterfaceList.Count];
// If our InterfaceList was not set, get all public properties.
if (InterfaceList == null)
Interfaces[0] = source.GetType();
else // Otherwise, get only the public properties from our passed InterfaceList
for (int i = 0; i < InterfaceList.Count; i++)
Interfaces[i] = source.GetType().GetInterface(InterfaceList[i].Name);
IEnumerable<PropertyInfo> propertyList = Enumerable.Empty<PropertyInfo>();
foreach (Type face in Interfaces)
{
if (face != null)
{
// If our SearchType is null, just get all properties that are not already empty
if (SearchType == null)
propertyList = face.GetProperties().Where(prop => prop != null);
else // Otherwise, get all properties that match our SearchType
propertyList = face.GetProperties().Where(prop => prop.PropertyType == SearchType);
// Reset each property
foreach (var property in propertyList)
{
if (property.CanRead && property.CanWrite)
property.SetValue(source, null, new object[] { });
}
}
else
{
// Throw an error or a warning, depends how strict you want to be I guess.
Debug.Log("Warning: Passed interface does not belong to object.");
//throw new Exception("Warning: Passed interface does not belong to object.");
}
}
}
And it's use:
// Clears all properties in object
ClearProperties(Obj);
// Clears all properties in object from MyInterface1 & MyInterface2
ClearProperties(Obj, new List<Type>(){ typeof(MyInterface1), typeof(MyInterface2)});
// Clears all integer properties in object from MyInterface1 & MyInterface2
ClearProperties(Obj, new List<Type>(){ typeof(MyInterface1), typeof(MyInterface2)}, typeof(int));
// Clears all integer properties in object
ClearProperties(Obj,null,typeof(int));
You'd probably need to save the values off in private fields, so that they can be restored later. Maybe something like this:
public class Truck
{
private static const string defaultName = "Super Truck";
private static const int defaultTires = 4;
// Use properties for public members (not public fields)
public string Name { get; set; }
public int Tires { get; set; }
public Truck()
{
Name = defaultName;
Tires = defaultTires;
}
public void ResetTruck()
{
Name = defaultName;
Tires = defaultTires;
}
}
You're essentially looking for the State Design Pattern
If you want a specific past "state" of your object you can create a particular save point to return every time you want. This also let you have a diferent state to backup for everey instance that you create. If you class has many properties who are in constant change, this could be your solution.
public class Truck
{
private string _Name = "Super truck";
private int _Tires = 4;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public int Tires
{
get { return _Tires; }
set { _Tires = value; }
}
private Truck SavePoint;
public static Truck CreateWithSavePoint(string Name, int Tires)
{
Truck obj = new Truck();
obj.Name = Name;
obj.Tires = Tires;
obj.Save();
return obj;
}
public Truck() { }
public void Save()
{
SavePoint = (Truck)this.MemberwiseClone();
}
public void ResetTruck()
{
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Count(); ++i)
properties[i].SetValue(this, properties[i].GetValue(SavePoint));
}
}
If you aren't using a Code Generator or a Designer that would conflict, another option is to go through C#'s TypeDescriptor stuff, which is similar to Reflection, but meant to add more meta information to a class than Reflection could.
using System.ComponentModel;
public class Truck {
// You can use the DefaultValue Attribute for simple primitive properites
[DefaultValue("Super Truck")]
public string Name { get; set; } = "Super Truck";
// You can use a Reset[PropertyName]() method for more complex properties
public int Tires { get; set; } = 4;
public void ResetTires() => Tires = 4;
public Truck() { }
public void ResetTruck() {
// Iterates through each property and tries to reset it
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(GetType())) {
if (prop.CanResetValue(this)) prop.ResetValue(this);
}
}
}
Note that ResetValue will also reset to a shadowed property if one exists. The priority of which option is selected is explained in the docs:
This method determines the value to reset the property to in the following order of precedence:
There is a shadowed property for this property.
There is a DefaultValueAttribute for this property.
There is a "ResetMyProperty" method that you have implemented, where "MyProperty" is the name of the property you pass to it.
You may represent an object state as a struct or record struct and then set the state to the default value in the Reset method like this:
public class Truck {
record struct State(string Name, int Tires);
private static readonly State _defaultState = new("Super Truck", 4);
private State _state = _defaultState;
public string Name => _state.Name;
public int Tires => _state.Tires;
public Truck() {}
public void ResetTruck() => _state = _defaultState;
}
It is probably the fastest way as well.
Also, a record struct will give you the trivial implementations of the ToString, Equals, GetHashCode.

Categories