Jump to content

  • Log In with Google      Sign In   
  • Create Account

class instance always null


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 inject   Members   -  Reputation: 550

Like
0Likes
Like

Posted 14 November 2012 - 07:29 AM

Hi gamedev, i have a bit of a problem Posted Image
I have a class with few properties called Token and a class called TokenOwner wich has a list of the Token class and few methods to operate with this list.
class TokenOwner
	{
		public List<Token> Tokens;
		public void AddToken(string name, double value)
		{
			Token t = new Token();
			t.Name = name;
			t.Value = value;
            Tokens.Add(t);  <- Here it throws exception
		}
		public void RemoveToken(string name)
		{
            Token t = Tokens.Find(x => x.Name == name);  <- Here it throws exception
			if (t != null) Tokens.Remove(t);
		}
		public bool HasToken(string name)
		{
			Token t = Tokens.Find(x => x.Name == name);  <- Here it throws exception
			if (t != null) return(true);
			else return(false);
		}
	}
class Token : TokenOwner
	{
		public string Name { get; set; }
		public double Value { get; set; }
	}
Now i want to add a token to a class inherited from TokenOwner. But every time i try to add token, it throws ObjectNullReference exception.
class Character : TokenOwner{}
class MyClass
	{
		Character myCharacter = new Character();
		myCharacter.AddToken("brokenleg", 0);
	}
I tried to figure out what's wrong, but i am programming for just a few days, so i have no idea what's wrong... If someone pointed out what's wrong and maybe tell me what would work, that would help a lot.

Edited by inject, 14 November 2012 - 08:08 AM.


Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9599

Like
0Likes
Like

Posted 14 November 2012 - 07:38 AM

Is that all your code? You never seem to initialize Tokens (i.e. I don't see a new List<Token>(); anywhere in your code).

#3 inject   Members   -  Reputation: 550

Like
0Likes
Like

Posted 14 November 2012 - 08:02 AM

Oh, seems like it slipped out, sorry about that.
class Token : TokenOwner
		{
				public string Name { get; set; }
				public double Value { get; set; }
			  
				public Token()
				{
				Tokens = new List<Token>();
				}
		}
And of course, Token class is inherited from TokenOwner.

Edited by inject, 14 November 2012 - 08:04 AM.


#4 inject   Members   -  Reputation: 550

Like
0Likes
Like

Posted 14 November 2012 - 08:25 AM

Ok, seems like i solved it by moving List<Token> initialization to TokenOwner class. Thanks.




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