471,306 Members | 863 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,306 software developers and data experts.

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



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
*** Sent via Developersdex http://www.developersdex.com ***
Feb 16 '06 #1
2 11135
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

<Beffmans> wrote in message news:uv**************@TK2MSFTNGP09.phx.gbl...


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
*** Sent via Developersdex http://www.developersdex.com ***

Feb 16 '06 #2
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");
}

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Feb 16 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Jinesh | last post: by
6 posts views Thread by WayneD | last post: by
1 post views Thread by Ray Cheung | last post: by
6 posts views Thread by Laura Carr | last post: by
6 posts views Thread by tshad | last post: by
9 posts views Thread by tshad | last post: by
3 posts views Thread by hazz | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.