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

  • Thread starter Thread starter dejas9000
  • Start date Start date
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'
 
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.
 
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
 
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.
 
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. :)
 
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
 
Back
Top