James P. Wright
James P. Wright

Reputation: 9131

Set value of Base class variable?

This may be a very stupid question and it's making feel like my brain has gone...but I cannot fathom how to set a protected or public variable from a Base class.

I have an Enum that is used in the Base class, but must be set in the Inheriting class. The Inheriting class is very little to no code so I SPECIFICALLY want to do this outside of a Method.

An example of what I want:

public class MyBase {
    protected myEnum;
}

public class MyClass : MyBase {
    myEnum = SomeValue;
}

If I set myEnum as a property with get/set, I can override it...but then I end up with many more lines of code.
If I override Page_Load I can access this.myEnum but again, I want to access it outside of a method as it is the only code in the Inheriting class.

Am I missing something completely obvious here?

Upvotes: 3

Views: 10685

Answers (3)

user166390
user166390

Reputation:

It is not possible to assign an "instance variable" unless one has (or is in) an instance :-) [C# does allow some compiler magic for fields defined within the current class definition and values assigned in the declaration; this does not expand to arbitrary assignments.]

While I would personally use the constructor of the derived class (or a method guaranteed to run at an appropriate time), one way that can be used to invert this, is to use a virtual getter:

Please note this example access a virtual method in the constructor (see Calling virtual method in base class constructor) which needs to be done with care: (The derived class may be in an "invalid state" insofar as it's constructor body has not run yet.)

class Base {
    protected virtual MyEnum DefaultEnumValue { get { return 0; } }
    MyEnum enumValue;

    Base () {
        enumValue = DefaultEnumValue;
    }
}

class Derived : Base {
    protected override MyEnum DefaultEnumValue { get { return MyEnum.Derived; } }
}

Once again, note the call to a virtual method, which can be avoided with a little more work in Base (e.g. wrap enumValue in a lazy-load getter itself), but for "shortest code"....

Happy coding.

Upvotes: 4

xxbbcc
xxbbcc

Reputation: 17327

Would this work for you?

BasePage.cs (BasePage, derives from Page):

class BasePage : Page
{
    ...
    private MyEnum _myenum;
    ...

    protected MyEnum EnumProperty
    {
        get { return _myenum; }
        set { _myenum = value; }
    }
}

Page.aspx.cs (derives from BasePage):

class _Page : BasePage
{
    // Nothing here for this
    ...
}

Page.aspx:

<%@Page ... Inherits="_Page" %>
...
<script runat="server">base.EnumProperty = MyEnum.Value;</script>
<html>
...
</html>

Upvotes: -1

SLaks
SLaks

Reputation: 887195

You need to create a constructor.
You cannot execute code outside a method.

Upvotes: 9

Related Questions