Passing in objects to class constructor
Hi, I am making an inventory management system and need to make a class that manages objects. I have a class called 'Rock', a class called 'Mud' and a class called 'Block'. The Rock and Mud class contain data about the rock and mud blocks. The Block class needs to take in an object in the class constructor which will set a local variable to that block type:
public class Block{
public Class blockType;
public int strength;
public Block(Class block){
blockType= block;
strength= block.strength;
}
}
How would I make it so I can pass any object type into the Block constructor and get the objects variables?
If looks like you're having trouble with the basics: declaring variables and simple function use. Take a look at that stuff in any C# manual. The same ideas apply to Constructors.
I understand how it works basically but, using inheritance, how would I pass in a rock into a block and store the block somewhere to be accessed. Rather than storing loads of different block types?
public Class blockType;
If you want to pass an object like structure use struct:
public enum BlockType
{
Rock,
$$anonymous$$ud
}
public struct BlockConfiguration
{
public BlockType blockType;
public int strength;
}
public class Block
{
public BlockType blockType;
public int strength;
public Block(BlockConfiguration blockConfiguration)
{
blockType = blockConfiguration.blockType;
strength = blockConfiguration.strength;
}
}
In the above code we have an enum to define the different types of blocks that are available, a struct to define the attributes a block can have and their types and the block class that you can pass the struct with the data like so:
Block blockInstance = new Block(new BlockConfiguration(BlockType.$$anonymous$$ud, 5));
In your case I would also recommend to look deeper at classes and their inheritance and generics.
okay so after researching enums I am still partly stuck, how would I assign a constant strength value for example for rock and a different value for mud so I don't have to enter the strength myself?
Your answer
Follow this Question
Related Questions
Hitting Serialization depth, need a better way to access parent class 1 Answer
NullReferenceException: Object reference not set to an instance of an object 0 Answers
C# Find specific object by getting one of its variables 0 Answers
Deserialize Json array with mixed types 0 Answers
Way of Finding/accessing a variable from another script though another variable? 1 Answer