[XNA] Dynamically Assign a Data Type ?

Started by
2 comments, last by ZaQ 11 years, 3 months ago

I am trying to brush up on my C# / XNA and I cannot figure out how to assign a data type at runtime.

I want to refer to all characters by creating a new Character.cs

Then inside of the Character.cs I instantiate a character type and choose a sub-.cs

Here is a representation of what I am used to doing in AS3:


Game1.cs

public Character Char = new Character();
 
CharType(Char, "Ninja");

public void CharType(Character Char, String chartype)
{
  if(chartype == "Ninja")
     Char.GameChar = new Ninja();
  else if(chartype == "Soldier")
     Char.GameChar = new Soldier();
}


Character.cs
 
var GameChar;

Is this possible in XNA / C#?

To be more clear, I am having trouble have the "var GameChar" in the Character.cs. I cannot find a way to program the variable into the class without first assigning a data type to it. I tried using an 'Object' and 'dynamic' but they wouldn't allow me to access variables within the GameChar variable.

If not, can anyone give me some pointers?

Advertisement
use an interface (ofc only properties and methods described in the interface will be accessible and if you want something more specific from soldier class you will have to cast CharacterType to Soldier with a check if the cast is succcesfsul)
public class Soldier : IFighter {} //interfacepublic class Ninja : IFighter {} //interface public class Character { public IFighter CharacterType { get; set; }  public Character(string type) {    if (type == "Ninja") {      CharacterType = new Ninja();    }    // etc }}

var is not a dynamic type. It's a static type determined at compile time, hence why you must assign a value to it.

Agreed about interfaces.

Thank you both, I'll read up on it.

This topic is closed to new replies.

Advertisement