Steffan Donal
Steffan Donal

Reputation: 2354

Accessing a class's properties two ways

I'm stuck on creating a class architecture to do this:

I have very many (About 78) types of block. The level for the game is made of these blocks. In the level's ByteArray, there are simply numbers, denoting the type of block. So for collision handling, I can just retrieve the number at the wanted position and get that block's properties. (Solid, selectable, visible, texture). BUT. I'll be reordering this list of blocks, and so, also need a way to access a block's properties by name.

So, I'd like to be able to access a block's properties via

Blocks[5].Properties

&

Blocks.Rock.Properties

Be aware that these are NOT instances, and I shouldn't have to instantiate them to access their properties.

Upvotes: 0

Views: 226

Answers (2)

KeithS
KeithS

Reputation: 71591

If you want Blocks[5].Properties as well as Blocks.Rock.Properties, Blocks must be a custom class with an indexer. The setup is similar to an operation:

public Block this[] (int index) 
{
   //getter logic here
}

Indexers can take integral types or strings, so you could use Blocks to wrap a dictionary and access values by key: Blocks["Rock"].Properties. That does involve "magic strings", which the compiler will not catch if you misspell.

The named getters are simple read-only properties:

public Block Rock { get{//getter logic here} }

If this were my application, I would create a singleton Blocks class. The blocks are integral to the game, used throughout its lifetime and you don't want to explicitly instantiate them; definition of a singleton scenario (and easier to change to a normally-scoped instance than if it were all static). That Blocks class would wrap a collection of Block objects, and that implementation is then hidden behind the Blocks accessors. You can use a List and search through their Properties using Linq (I assume the properties of a Block would include the BlockID as well as its name), or you can choose the index or name of a block to be the key of a Dictionary of Blocks.

Upvotes: 1

Novikov
Novikov

Reputation: 4489

Since different block types are integers you could use a map/dictionary/associative array.

Dictionary<string, int> BlockTypes = new Dictionary<string, int>();
BlockTypes["Rock"] = 1337;

Upvotes: 0

Related Questions