Usually in java
you can declare an instance variable then initialize it inside the constructor or inside a method.
But When i tried to do that in C#
it gave me an error saying it needs to be a static variable.
In this image I declared an instance variable of MailMerger object then I initialized it inside the constructor. But when I tried to use the instance, it gave me an error asking for it to be static
.
Can anyone please explain to me the reason behind that please? Thank you in advance.
CodePudding user response:
You are calling a non static member from a static method which is not allowed as the error says.. You can fix it by Making MailMerger
static as well
Class Program
{
static MailMerger merge;
//rest of your code
}
Another option is creating an instance of MailMerger
within the static method.
CodePudding user response:
The reason is the Main
method is static while merge
variable is in instance-scope.
You should change the constructor to static and also the variable.
CodePudding user response:
You declered a MailMerger
in Program
constructor, but you have to create an instance of Program
in Main
method. In your Main
method you are calling merge
which was never initialized. If you create a new instance of Program
class, like this:
Program p = new();
Than you can call the the merge
field:
p.merge.Merge();