Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class fields from partial class

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?

like image 523
Pepijn Olivier Avatar asked Nov 09 '10 11:11

Pepijn Olivier


2 Answers

A common problem is having the partial classes in different namespaces. Namespaces are part of the Class name, namespace1.myClass and namespace.a.myClass are handled as two completely seperate classes.

According to MSDN, each part of a partial class should:

  • have the partial modifier
  • have the same class name
  • be in the same namespace
  • be in the same assembly or DLL
  • have the same visibility (like public, private, etc)
like image 149
Sven Avatar answered Nov 09 '22 23:11

Sven


There are a few things you need to fix with the code you posted:

When using partial classes in C# all parts of the class must be declared as partial classes

You have:

 public class myClass {}
 public partial class myClass {}

Which needs to become:

public partial class myClass {}
public partial class myClass {}

Secondly, you're trying to set:

myString="newString";

but myString is a public property without a setter.

So either you add a setter when declaring myString:

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

or just use:

_myString="newString";

in your second partial class file.

like image 26
Khalos Avatar answered Nov 10 '22 01:11

Khalos