"a field initializer cannot reference the nonstatic method xxx" error

  • Thread starter Thread starter TS
  • Start date Start date
T

TS

I am trying to create a page template. I am trying to set the value of a
field to the return value from a method. What do I have to do to get m_form
set to the value returned from a method? (the compiler won't let me do
this:)

// Form in the page
public HtmlForm m_form = FindFormTag();

public HtmlForm FindFormTag()
{
foreach(Control c in this.Controls)
{if(c.GetType() == typeof(HtmlForm))
{
return (HtmlForm) c;
}
}
return new HtmlForm();
}

thanks for the response.
 
Thanks for Peter's quick response.

Hi TS,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you received a compiler error when
trying to assign the return value of a method to a field as its initial
value. If there is any misunderstanding, please feel free to let me know.

As far as I know, it is a language specification of C# that we cannot
assign initial value to a field with the return value of a method, a
property or a field. So if you wish to achieve this, please try to set the
value in the constructor of the class.

HTH. If anything is unclear, please feel free to reply to the post.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
TS said:
I am trying to create a page template. I am trying to set the value of a
field to the return value from a method. What do I have to do to get m_form
set to the value returned from a method? (the compiler won't let me do
this:)

// Form in the page
public HtmlForm m_form = FindFormTag();

public HtmlForm FindFormTag()
{
foreach(Control c in this.Controls)
{if(c.GetType() == typeof(HtmlForm))
{
return (HtmlForm) c;
}
}
return new HtmlForm();
}

The reason it won't let you do this is because when the initializer
takes place, your object is only partially constructed. In particular,
the Controls collection may well not have been initialized at all. I
suggest you set m_form from the constructor.

I also suggest you use

if (c is HtmlForm)

unless you're *deliberately* preventing it from finding instances of
classes derived from HtmlForm.
 

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

Back
Top