"An object reference is required for the non-static field, method, orproperty" compilation error gen

D

dejas9000

Hello.

I have see the error in the subject line pop up before when attempting
to reference a non-static member from a static context, however I am
now having this issue when referencing a non-static member from a non-
static context and can't quite figure out why. Can anyone shed some
light on this please?


public class DebugParser : Parser
{
protected internal IDebugEventListener dbg;
...
}

public class AGLParser : DebugParser
{
public IDebugEventListener mydbg = dbg;
...
}

results in:

An object reference is required for the non-static field, method, or
property 'DebugParser.dbg'
 
S

Scott Roberts

I assume that the message is telling you that "dbg" has not been
initialized.
 
J

Jon Skeet [C# MVP]

I have see the error in the subject line pop up before when attempting
to reference a non-static member from a static context, however I am
now having this issue when referencing a non-static member from a non-
static context and can't quite figure out why. Can anyone shed some
light on this please?

You can't refer to "this" within a variable initializer, basically.
You need to put the assignment in the constructor.

On a stylistic point, I prefer to make *all* fields private.
 
P

Peter Duniho

An object reference is required for the non-static field, method, or
property 'DebugParser.dbg'

Have you tried writing it as "mydbg = this.dbg"?

I don't recall off the top of my head whether you can even reference base
class members legally in initializers for derived classes. I thought you
could, but if so you might have to specify the reference explicitly. The
fact that you're getting an error though suggests that maybe this just
isn't allowed. Writing it as "this.dbg" would, in this case, probably
generate a different error and one that's more specific to the restriction
preventing the initialization.

Or, it might just work. :) Either way, that should help.

Pete
 
I

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

Hi,


An object reference is required for the non-static field, method, or
property 'DebugParser.dbg'

Have you tried writing it as "mydbg = this.dbg"?

I tried it :)
And it gives you "this" is not available in the current context.
 
P

Peter Duniho

I tried it :)
And it gives you "this" is not available in the current context.

Which is, just as I'd guessed, a more specific error that more precisely
describes why the code won't work. :)
 
C

christery

Just a thought...
Are you trying to use the object being created as already created?
that is is there a "this"
Oh that looks like zen, well, what came first? the hen or the egg
//CY
 

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