I am learning C# and i get this weird error while trying out example in LinqPad.

public class UnitConverter
{   
    int ratio;
    public UnitConverter(int UnitRatio)
    {
        ratio = UnitRatio;
    }

    public int Convert(int data)
    {
        return ratio * data;
    }
}

class Test
{
    static void Main()
    {
        UnitConverter FeetToInchesConverter = new UnitConverter(12);
        Console.WriteLine(FeetToInchesConverter.Convert(10));
    }
}

I get this error

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

What wrong am i doing ?

有帮助吗?

解决方案

You need to remove the Class around the method main

static void Main()
{
    UnitConverter FeetToInchesConverter = new UnitConverter(12);
    Console.WriteLine(FeetToInchesConverter.Convert(10));
}

The Main method is part of the internal class UserQuery and it is used as entry point for your script. So, if you hide it inside your own class then, probably, LinqPAD cannot find the entry point. What happen next is probably some invalid reference. For example, if you remove all the code of the class Test (Main included) LimqPAD raises the same error

其他提示

The problem is that your main() is in class, in order to run the program in LINQPad remove the class Test around the main() method

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top