C# value/reference passing? - c#

I have a declared entity of a class, and want to assign different pre-made templates to it without the templates ever changing. Using a const doesn't seem to do the trick.
Example:
Weapon w1;
w1 = Sword; // premade weapon.
w1.reducedamage(1); // for example a debuff
In this case the premade weapon's damage would be decreased, and it would no longer be available as a template. This problem becomes more profound with enemies.
Example:
Enemy enemy;
enemy = enemies[r] // r being a randomly generated integer and enemies a list of enemy templates
Fight(player,enemy); // this method would resolve a fight between the two entities of the type Character.
This problem would not be visible in the player class, since player is a single reference being passed along all the game methods - because there is only one player. Every time the player fights, an enemy template would be "corrupted".
How would I create templates or classes/structs in general that always pass by value, meaning that the properties of a first class would have the same values as a second, without any relationship between the two classes?
The only success I've gotten with this is to create a method that manually copies each attribute of every class that has a template onto another entity of the same class; but this is extremely unpractical since it needs constant upgrading whenever a new class is added, or an old one changed.

I must be missing something. This seems like a reasonably simple issue that is easily solved by inheritance, perhaps in conjunction with some sort of Factory. First, you don't want to use a reference to a single instance, you want to create a new instance each time so it is a unique object. I prefer classes over structs, but you could easily create a new struct as well. You could use a Factory to create various pre-configured instances of the objects that have pre-defined values. For example, the Sword of Damocles or the Sword of Destiny.
public static class WeaponFactory
{
public static Weapon CreateSword(SwordType type)
{
var sword = new Sword(); // plain, old default sword
// override properties based on type
switch (type)
{
case SwordType.SwordOfDamocles:
sword.FallTime = GetRandomFutureTime();
break;
case SwordType.SwordOfDestiny:
sword.Invincible = true;
break;
...
}
return sword;
}
...
}
Alternative using Actions
public static class WeaponFactory
{
public static Weapon Create<T>(Action<T> decorator) where T : IWeapon, new()
{
var weapon = new T();
decorator(weapon);
return weapon;
}
public static void SwordOfDamocles(Sword sword)
{
sword.FallTime = GetRandomFallTime();
}
public static void SwordOfDestiny(Sword sword)
{
sword.Invincible = true;
}
}
var weapon = WeaponFactory.Create(WeaponFactory.SwordOfDamocles);

What you want is object cloning. You can implement it via the ICloneable interface[1]. That requires that you implement your own cloning mechanism though--you have to do the heavy lifting.
However, what you probably should do instead is just have the constructor take a parameter that represents the template you want, and then fill the properties of the object in question based on that template. That's the direction I go when I want to make duplicate things with a base set of values.

You could do actual copying (e.g. provide a copy constructor as in http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx ), but what I've seen most often in such cases is a factory pattern, e.g. Weapon w1 = Weapon.CreateSword(); or Enemy e=Enemy.CreateEnemyOfType(r);

you could build a method to return multiple enemies in either a generic collection or array into your enemy class. Something like:
public shared function getEnemies(num as integer, type as string) as list(of clsEnemy)
dim enemyGroup as list(of clsEnemy)
for i = 0 to num - 1
dim thisEnemy as new clsEnemy(type)
enemyGroup.add(thisEnemy)
next
return enemyGroup
end function

Contrary to copying objects to implement some kind of "applied object" pattern, it's good to keep in mind it's not the sword "base item" that is being altered, but the item your player is carrying.
For example, a given sword, say "rusty old sword", will always have a base damage of 50. Now if someone applies "old stuff gets better magic" to it, it's not the "rusty old sword" that gets more damage: if some other player that hasn't got that kind of magic picks up the item, it's back to its base damage of 50.
So if you implement some kind of EquippedWeapon (or even EquippedItem) class, you can let your player equip weapons and give it extended properties. Something like this to declare a Sword:
interface IWeapon
{
int Damage { get; }
}
class Sword : IWeapon
{
public int Damage { get; private set; }
public Sword()
{
this.Damage = 50;
}
}
Now we have a sword with a base damage of 50. Now to let the player carry this sword:
interface IDamageModifier
{
int Damage { get; set; }
}
class EquippedWeapon : IWeapon
{
public int Damage
{
get
{
return CalculateActualDamage();
}
}
public List<IDamageModifier> DamageModifiers { get; set; }
private IWeapon _baseWeapon = null;
public EquippedWeapon(IWeapon weapon)
{
_baseWeapon = weapon;
}
private int CalulcateActualDamage()
{
int baseDamage = _baseWeapon.Damage;
foreach (var modifier in this.DamageModifiers)
{
baseDamage += modifier.Damage;
}
return baseDamage;
}
}
A weapon contains a list of active modifiers, that affect the damage of the carried item, but not the base item. This way you can share one Sword instance with many (non-)playable characters.
Now if the player gets attacked and that attack has a damage effect, you simply apply that to the item(s) the player is carrying, so each successive attack from that player will have those effects applied:
class Player
{
public EquippedWeapon PrimaryWeapon { get; set; }
public Player()
{
this.PrimaryWeapon = new EquippedWeapon(new Sword());
}
public void UnderAttack(Attack attack)
{
// TODO: implement
if (attack.Buffs...)
{
this.EquippedWeapon.DamageModifiers.Add(attack.Buffs);
}
}
}

I wrote an answer answering your question directly. But now I see that all you want is to create items that are the same but not linked.
That's what happens anyway when you create an instance. You don’t have to do anything.
If you have:
class Class1
{
public int i;
}
Then:
Class1 c1 = new Class1() { i = 1 };
Class1 c2 = new Class1() { i = 2 };
Text = c1.i.ToString();
Prints "1", not "2".
And if you mean you want a "Player" class with sub-classes "Friend" and "Foe" - That's what inheritance is for:
class Player
{
}
class Friend : Player
{
}
class Foe : Player
{
}
EDIT:
Perhaps this will make the task easier: (The "Duplicate" method)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Class1 c1 = new Class1() { i = 1, j = 2 };
Class1 c2 = Duplicate(c1);
c1.i = 3;
Text = c2.i.ToString();//Prints "1";
}
public Class1 Duplicate(Class1 c)//Duplicates all public properties.
{
Class1 result = new Class1();
PropertyInfo[] infos = typeof(Class1).GetProperties();
foreach (PropertyInfo info in infos)
info.SetValue(result, info.GetValue(c, null), null);
return result;
}
}
public class Class1
{
public int i { get; set; }
public int j { get; set; }
}

Related

How to change a class variable?

I have a class in a very basic C# console game (text adventure) that I would like to modify a variable elsewhere in the code. I understand that C# does not allow global variables, but that is essentially what I am looking for.
I am a beginner at programming. I am stumped and I've been unable to find an answer to this question. It's really a question of scope that I'm after; what variables can "talk" to each other. I'll include a simple example below.
All of these fields in the class will
be modified elsewhere within various methods.
class Player
{
public int health = 100;
public string armor = "none";
public string gun = "none";
public int money = 1000;
}
public static void AddMoney()
{
var NewPlayer = new Player();
NewPlayer.money += 1500;
}
So I want to basically know what is expected of me to do if global variables aren't a thing in C#.
There's a few ways of updating instance variables in C#: Using properties or setters like in Java or instance methods. Following code shows you a few of those.
Ultimately, what you want to do is pass a reference to the instance of the player to different methods and let them use the properties/methods to update the instance variables:
namespace Test
{
class Program
{
static void Main(string[] args)
{
var p1 = new Player();
p1.Health = 5000;
p1.Armor = "Helmet";
p1.AddMoney(200);
Console.WriteLine($"Health: { p1.Health }");
var enemy = new Enemy();
enemy.Shoot(p1);
Console.WriteLine($"Health after being shot: {p1.Health}");
}
}
class Player
{
private string armor;
private int money;
public int Health { get; set; }
public string Armor
{
get => armor;
set
{
Console.WriteLine("Updating armor.");
armor = value;
}
}
public int Money { get; private set; }
public void AddMoney(int money)
{
// More complex logic here, example: synchronization.
this.money = money;
}
}
class Enemy
{
public void Shoot(Player p)
{
p.Health -= 500;
}
}
}
This is the object-oriented way of doing things. As for global variables in the sense of application-wide variables, you can refer to this.
You can also make the Player a singleton. This is more a design choice than actual C# stuff. I'm not going to go into singleton pattern here. If you search singletons and their pros and cons, you will get an earful of that :)
Disclaimer: you could make Player a static class, which would probably behave how you want, but doing so is ill-advised as it limits you to a single player object and can't easily be unit tested, amongst other problems. See When to use static classes in C#.
You have to understand that you Player is a class. Think of it as a blueprint for how a Player object should look. I usually go to a car analogy for this: you buy two Toyota Priuses. Identical in every way. You take one to a spray shop and have a design painted on it. Has the other Prius changed? No. It's the same with var player1 = new Player(); var player2 = new Player(); - they are both of type "Player", but they are not the same player.
Now consider your AddMoney method:
public static void AddMoney()
{
var NewPlayer = new Player();
NewPlayer.money += 1500;
}
You're creating a player that only exists within the AddMoney method. Once outside, it effectively doesn't exist anymore (stuff isn't deleted from memory immediately, but garbage collection isn't a topic you should be concerned with just yet).
Since Player is a class, it's a reference type, which means that passing it to a method will pass a reference to the same object in memory. This means that we can change the object in AddMoney and it will be reflected in the caller. Note that we can't replace the object - for that you would need the ref keyword (but that's another topic too).
public static void AddMoney(Player player)
{
player.money += 1500;
}
Example:
var player = new Player();
player.money = 8500;
Console.WriteLine(player.money); // 8 500
AddMoney(player);
Console.WriteLine(player.money); // 10 000
Try it online
Alternatively, if you want to create a player, you could create a factory method:
public static Player CreatePlayer()
{
return new Player
{
money = 1500
};
}

Merging two lists of different objects into one. C# Unity2D

First I want to give some context. I got two different classes (class Player and class Enemy), each class contains different data, but they both hold the value "int Initiative".
public class Enemy : MonoBehaviour
{
public int initiative;
//More code
}
public class Player : MonoBehaviour
{
public int initiative;
//More code
}
On my project I have several units from both classes and they are stored on 2 different lists of objects
private List<Player> players;
private List<Enemy> enemies;
void Awake()
{
players = new List<Player>();
enemies = new List<Enemy>();
}
Is not shown in the code, but each unit is being sent and storaged on those list depending on their class.
Now my question:
Is there any way of combining both list into a single list keeping all the different objects? (I tried to do this, but didn't get far)
If there is no way of combining both lists because they contain different types of objects, could I create a single list that only storage the int initiative, type of object as well as the position on their previous list? (so I can refer to the lists (players and enemies) when needed. Please explain me how I could achieve this (if possible with some code).
With this I am trying to create some sort of system that will look at the initiative of each unit and call them in order starting for the one that has the highest.
Please I am pretty new in C# and coding in general, so excuse me if the question is too simple, or doesn't make sense.
Thanks in advance :)
You can do something like this:
public class MonoBehaviour
{
public int initiative;//Since you are using inheritance this can be set here
}
public class Enemy : MonoBehaviour
{
//More code
}
public class Player : MonoBehaviour
{
//More code
}
Here is the code to merge them into one list:
List<MonoBehaviour> list = new List<MonoBehaviour>()
list.Add(new Enemy());
list.Add(new Player());
When you want to process them differently somewhere for example you create a method as below:
void ProcessList(List<MonoBehaviour> list)
{
foreach(var l in list)
{
if(l is Enemy)
{
var enemy = (Enemy) l;
//process the enemy
}
else
{
var player = (Player) l;
//process as a player
}
}
}
You can use inheritance. Having base for both Enemy and Player.
public class AliveEntity
{
public string Name {get;set;}
public double HP {get;set;}
}
public class Player : AliveEntity
{ /*...*/ }
public class Enemy : AliveEntity
{ /*...*/ }
And then the list could be List<AliveEntity>.

How do I make T work with intherited classes?

I'm programming a dungeon generator for a roguelike. I've a base class called Room. It contains methods that can be inherited by other types of rooms. It looks like this but then a little more advanced
class Room
{
protected virtual void Construct() { /*make square room here*/ }
}
class RoundRoom : Room
{
protected override void Construct() { /*make round room here*/ }
}
My class that generates rooms needs to be "fed" with rooms to generate. The room handles the construction, and I've different types of rooms. And I want it to have it that certain specific rooms can be generated based on some conditions or chances.
So I feed it with different types of rooms. First I thought of this:
class RoomEntry
{
public Point chance;
public Room room;
}
And then have an array of it
RoomEntry[] entries;
And then just feed it
Generator.Feed(entries[random.Next(0, 10)].room); // just an example
But that won't work! If I edit the room in the generator, It'll change in RoomEntry too! And I need to use it quite a few times!
So if I would make new rooms based on some room type... It'll work!
So I came up with this:
class RoomPlanner
{
class RoomEntry<T> where T : Room, new()
{
public Point chance;
T r;
public Room RoomToBuild()
{
return new T();
}
}
RoomEntry<Room>[] entrys;
public void Foo()
{
entrys = new RoomEntry<Room>[10];
for (int i = 0; i < entrys.Length; i++)
{
entrys[i] = new RoomEntry<RoundRoom>();
}
}
}
But that's not possible. I'm getting this error:
Cannot implicitly convert type 'Super_ForeverAloneInThaDungeon.RoomPlanner.RoomEntry<Super_ForeverAloneInThaDungeon.RoundRoom>' to 'Super_ForeverAloneInThaDungeon.RoomPlanner.RoomEntry<Super_ForeverAloneInThaDungeon.Room>'
So, how do can I make it accept classes that inherit from Room, or how do I take a different approach to this problem?
It's not an duplicate of this. That's a different problem, and I do not have enough information to fix my problem entirely out of it.
The problem is that covariant/contravariant type parameters can only be used with interface or delegate types. (More information on that in this MSDN article.) Essentially, there is no way to declare a RoomEntry<T> that is contravariant with RoomEntry<Room>, even with the constraint that T : room.
You could get around this by defining an IRoomEntry interface that is implemented by RoomEntry<T>, like this:
interface IRoomEntry
{
Room RoomToBuild();
}
class RoomPlanner
{
class RoomEntry<T> : IRoomEntry
where T : Room, new()
{
public Point chance;
T r;
public Room RoomToBuild()
{
return new T();
}
}
IRoomEntry[] entrys;
public void Foo()
{
entrys = new IRoomEntry[10];
for (int i = 0; i < entrys.Length; i++)
{
entrys[i] = new RoomEntry<RoundRoom>();
}
}
}
Seems like you just want to Clone the room before feeding it to the Generator. You could just add a Clone method to your Room class:
Room Clone() { return (Room)this.MemberwiseClone(); }
And then feed it like so:
Generator.Feed(entries[random.Next(0, 10)].room.Clone());

C# Cross-Class object

I'm working on very simple Roguelike game (just for myself) and get a question:
As it is not possible to create a cross-class struct-object (entity in the game case) that could be accessible from any class of my program, what to use to create a cross-class object? I was thinking of something like storing all newly created object (enities) in a static object array, but I guess there is more simple solution on this problem.
Question itself: How to create a cross-class accessible object(s) with your own properties?
Thanks everybody, I found what I was searching for.
It seems like you tried passing around a value type (a struct) between different classes and you noticed that when you update the value in one place it doesn't change the value in another place.
That's the basic difference between value types and reference types.
If you are creating the struct yourself you may want to instead define it as a class.
If not, you could wrap all your structs in a class and pass the class around as your state object.
If all you have is simply a list of the same type of struct (like Points), just pass the List itself around. C# collections are implemented as classes.
public class GameState
{
public Point PlayerLocation { get; set; }
public List<Point> BulletPoints { get; set; }
public double Health { get; set; }
}
Now you can create a GameState and pass it around to different classes:
public class Game
{
private GameState _state = new GameState();
private BulletUpdater _bulletUpdater = new BulletUpdater();
public void Update()
{
_bulletUpdater.UpdatePoints(_state);
// Points have now been modified by another class, even though a Point is a struct.
}
}
public class BulletUpdater
{
public void UpdatePoints(GameState state)
{
for (int i = 0; i < state.BulletPoints.Count; i++)
{
Point p = state.BulletPoints[i];
state.BulletPoints[i] = new Point(p.X + 1, p.Y + 1);
}
}
}
Just remember in the above code if I were to write:
Point p = state.BulletPoints[i];
p.X += 1;
p.Y += 1;
That wouldn't affect the original point! When you read a value type from a list or from a class into only copies the value into a local variable. So in order to reflect your changes in the original object stored inside the reference type you need to overwrite it like so:
state.BulletPoints[i] = p;
This same principal is why the following also will not work:
state.PlayerLocation.X += 5; // Doesn't do anything
state.PlayerLocation.Y += 5; // Also doesn't do anything
The compiler would tell you in this case that you are doing something wrong. You are only modifying the returned value of the property, not the backing field itself. You have to write it like so:
state.PlayerLocation = new Point(state.PlayerLocation.X + 5, state.PlayerLocation.Y + 5); // This works!
You can do the following:
Using IoC Framework, like Ninject. You can setup Ninject to create single instance for all usages.
The other option is to use Singleton pattern design pattern
And the third one is to use static property
It sounds like you want to use the Singleton pattern:
http://en.wikipedia.org/wiki/Singleton_pattern
Here is an example of what this would look like in C#:
public class Singleton
{
static Singleton()
{
Instance = new Singleton();
}
public static Singleton Instance { get; private set; }
}
It's possible. What about public and static class?
public static class CrossClassObject
{
public static object MyProperty { get; set; }
public static void MyMethod() {}
}
Of course this class should be placed in the same namespace that other ones.
How to use it?
class OtherClassInTheSameNamespace
{
private void SomeMethod()
{
var localVariable = CrossClassObject.MyProperty; // get 'cross-class' property MyProperty
CrossClassObject.MyMethod(); // execute 'cross-class' method MyMethod()
}
}
No idea what you are trying to achieve... but if you want a list of objects accessible 'cross-class', just make a static class with a list of objects and then when you reference your class from any other class, you will have access to its list of objects. Here is something like that:
public static class ObjectController
{
private static IList<object> existingObjects;
public static IList<object> ExistingObjects
{
get
{
if (existingObjects == null)
{
existingObjects = new List<object>();
}
}
}
}
public class MyObject
{
public MyObject()
{
ObjectController.ExistingObjects.Add(this);
}
public void Delete()
{
ObjectController.ExistingObjects.Remove(this);
}
}
Then you can add stuff like
MyObject newObj = new MyObject();
//// other stuff... This object should now be visible to whatever other class references ObjectController
newObj.Delete();

C# Reaching objects from a different class

I'm learning C# and I'm trying to make a game and I have a problem. I have two classes that I call Item and Weapon, Weapon looks something like this:
class Weapon : Item
{
int damage;
int durability;
public void asd()
{
Weapon shortSword = new Weapon();
shortSword.dmg = 5;
shortSword.durability = 20;
Weapon woodenBow = new Weapon();
woodenBow.dmg = 3;
woodenBow.durability = 15;
}
}
Then I have another class containing different methods, one of them is called when the player walks on an item and its supposed to randomize that item. But I can't reach the objects in Weapon from this other class. How do I reach them, or solve this problem?
There is a problem with your design. The method that creates weapons shouldn't be an instance method on the Weapon class. It could perhaps be a static method, or perhaps even a method on some other class.
Your method should return the weapons in a collection or as an IEnumerable.
public class Weapon : Item
{
public int Damage { get; set; }
public int Durability { get; set; }
// Consider moving this method to another class.
public static IEnumerable<Weapon> CreateWeapons()
{
List<Weapon> weapons = new List<Weapon>();
Weapon shortSword = new Weapon { Damage = 5, Durability = 20 };
weapons.Add(shortSword);
Weapon woodenBow = new Weapon { Damage = 3, Durability = 15 };
weapons.Add(woodenBow);
return weapons;
}
}
I also used the object initializer syntax to make the code more concise, and tidied up some of your method/property naming.

Categories