简体   繁体   中英

Null reference exception was unhandled in c#

For example in section a: i have a random number and in the section b: i want to multiply that random number by 2 but it has to be in a function and then section c: has to add 10 and so on. I guess this is very simple for you guys. and i am sure i am writing very silly codes but i am not a programmer.

thanks.

class Program
{
    static void Main(string[] args)
    {
        Boot boot = new Boot();
        Game game = new Game();

        Console.WriteLine("Matrix Lengte: " + game.Matrix);
        Console.WriteLine("Lengte boot: " + boot.Lengte);

        Console.ReadLine();

class Game
{
    private Boot boot;
    private int matrix;

    public int Matrix
    {
        get { return matrix; }
        set { matrix = value; }
    }

    public Game()
    {    
        matrix= boot.Lengte*2;
    }

    internal Boot Boot
    {
        get { return boot; }
        set { boot = value; }
    }

By default fields have their default values, which is null for reference types. So, just add boot initialization:

public Game()
{
    boot = new Boot(); // or pass via constructor parameter
    matrix = boot.Lengte * 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM