Alex Rivera | Logout

Access class fields from partial class

Asked 2010-11-09T11:14:20.907
14

I'm currently in a scenario in which I have to make use of partial classes. In this partial class I have a few methods that need to address fields in the other class.

for example

Edit: I'm sorry: the first class is already declared partial!

public partial class myClass
{        
    private string _myString;

    public string myString
    {
        get { return _myString; }
        set { _myString = value; }
    }
}

and

public partial class myClass
{
    public void doSomething()
    {
        myString = "newString";
    }
}

The compiler says myString doesn't exist in the partial class!

How can I overcome this problem?

Edit
Report

1 Answer

1

When I put your code into Visual Studio I got a different error:

myString = "newString";
Error   Property or indexer 'ConsoleApplication1.Program.myClass.myString' cannot be assigned to -- it is read only

If I change it to this, it works fine:

_myString = "newString";

Edit:

You don't need to mark a class as partial in both palaces, this compiles fine:

    public class myClass
    {

        private string _myString;

        public string myString
        {
            get { return _myString; }
        }
    }


    public partial class myClass
    {

        public void doSomething()
        {
            _myString = "newString";
        }

    }
answered 2010-11-09T11:18:27.680

Your Answer