error: An object reference is required for the nonstatic field......


B

Beffmans

Hi

When I run this code:

using System;

namespace DelegateProject
{
public delegate void MyDelegate(string s);

class Class1
{

public void SayHello(string s)
{
Console.Write(s);
}

static void Main(string[] args)
{
MyDelegate MyInstDel = new MyDelegate(SayHello);
MyInstDel("Hello");
}
}
}



I get the error:

An object reference is required for the nonstatic field, method, or
property 'DelegateProject.Class1.SayHello(string)'


??

What could be wrong?

thanks

Bert Effmans
 
Ad

Advertisements

V

vinu

Hi.

This is because you calling non static method in a static method (main)

change the declaration of SayHello to

pubic static void SayHello(string s)


class Class1

{

public static void SayHello(string s)

{

Console.Write(s);

}

static void Main(string[] args)

{

MyDelegate MyInstDel = new MyDelegate(SayHello);

MyInstDel("Hello");

}


}





Regards
Vinu
 
Ad

Advertisements

I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


main is a static method, it's not associated with any instance, SayHello is
an instace method, you need to create an instance before call it, change
your code to:

static void Main(string[] args)
{
Class1 instance = new Class1();
MyDelegate MyInstDel = new MyDelegate( instance.SayHello);
MyInstDel("Hello");
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top