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?
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
Which needs to become
Secondly, you're trying to set
but
myString
is a public property without a setter.So either you add a setter when declaring
myString
or just use
in your second partical class file.
A common problem is having the partial classes in different namespaces. Namespaces are part of the Class name,
namespace1.myClass
andnamespace.a.myClass
are handled as two completely seperate classes.According to MSDN, each part of a partial class should:
partial
modifierYou simply have to mark the class as
partial
in both places, not just one of them.Assuming that both declaration refer to the same namespace, your first declaration does not contain the partial keyword:
http://msdn.microsoft.com/en-en/library/wa80x488(v=VS.80).aspx
When I put your code into Visual Studio I got a different error:
If I change it to this, it works fine:
Edit:
You don't need to mark a class as partial in both palaces, this compiles fine: