Jump to content

  • Log In with Google      Sign In   
  • Create Account


[XNA] Dynamically Assign a Data Type ?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 ZaQ   Members   -  Reputation: 120

Like
0Likes
Like

Posted 13 January 2013 - 01:51 AM

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, 13 January 2013 - 02:05 AM.


Sponsor:

#2 DpakoH   Members   -  Reputation: 927

Like
0Likes
Like

Posted 13 January 2013 - 02:57 AM

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, 13 January 2013 - 02:58 AM.


#3 phil_t   Crossbones+   -  Reputation: 3222

Like
0Likes
Like

Posted 13 January 2013 - 07:56 AM

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.



#4 ZaQ   Members   -  Reputation: 120

Like
0Likes
Like

Posted 13 January 2013 - 12:28 PM

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






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS