• Advertisement
Sign in to follow this  

[XNA] Dynamically Assign a Data Type ?

This topic is 1834 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Edited by ZaQ

Share this post


Link to post
Share on other sites
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 }}
Edited by DpakoH

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement