Linked Questions

Popular Questions

Object always returns null when trying to access in different class

Asked by At

I'm creating an object of a class in my Form2() and trying to access the properties I set there in my other class by initializing it first

I thought Interfaces were my solution but I can't get my head around it, tried accessing it through a public method none really helped, I'm always getting null.

Form2() newForm = new Form2();

newForm.newChar.Race

while my Form2.cs contains

public Character newChar = new Character("Human", Race.HUMAN);

I'm trying to make a switch statement for Race property, but once again, it always throw exception:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Character.cs

    public class Character
    {
        private Race m_race;
        private string m_characterName;

        public Character(string characterName, Race race)
        {
            this.m_race = race;
            this.m_characterName = characterName;
        }

        public Race Race
        {
            get { return m_race; }
            set { m_race = value; }
        }

        public string Name
        {
            get { return m_characterName; }
            set { m_characterName = value; }
        }
    }

Where I'm getting null:

           switch (newForm.Character.Race)
            {
                case Race.HUMAN:
                    label11.Text = "Human";
                    break;
                case Race.ORC:
                    label11.Text = "Orc";
                    break;
                case Race.ELF:
                    label11.Text = "Elf";
                    break;
                case Race.DEMIHUMAN:
                    label11.Text = "Demi-Human";
                    break;
                default:
                    label11.Text = "ERROR";
                    break;
            }
        }```


Related Questions