i need to define a class partially in seperate assemblies. actually i need to redefine a class partially, that is already defined in an assembly written in C++ Cli, but this is maybe a different question.
for the case, all codes written in c#, i have a baseclass definition in basenamespace assembly
using System;
namespace BaseNameSpace
{
public class BaseClass
{
public int Num;
public double dNum;
public BaseClass(int s, double d)
{
Num = s;
dNum = d;
}
public virtual void Wrt()
{
Console.WriteLine("{0},{1}", Num, dNum);
}
}
}
i add another assembly project called derivedclassSpace and declare a derivedclass derived from baseclass. i also add a partial class definition to this project.
using System;
using BaseNameSpace;
namespace BaseNameSpace
{
public partial class BaseClass
{
public void Mult()
{
Num *= 2;
}
}
}
namespace DerivedNameSpace
{
public class DerivedClass : BaseClass
{
public DerivedClass(int s)
: base(s, 0)
{
}
public override void Wrt()
{
Mult(); // mult line
base.Wrt();
}
}
}
when i build the solution i get
'DerivedNameSpace.DerivedClass.Wrt()': no suitable method found to override
if i remove the partial class lines and mult line, everything is normal.
am i using the concept of partial keyword? how can i get rid of the error?
You cannot define a partial class across assemblies. Partial classes (and partial methods) are just compiler features that allow you to split up the definition across files. Once the assembly is compiled, there is a single class. Your only real option is to inherit from the base class, add your function, then have further derived classes inherit from this new class.
If all you're trying to do is add a method to an existing class, however, you might consider an extension method. While this doesn't actually add it to the class per se, it does allow you to write your code as if it had.
namespace BaseNameSpace
{
public static class BaseClassExtensions
{
public static void Mult(this BaseClass instance)
{
instance.Num *= 2;
}
}
}
namespace DerivedNameSpace
{
public class DerivedClass : BaseClass
{
public DerivedClass(int s)
: base(s, 0)
{
}
public override void Wrt()
{
Mult(); // mult line
base.Wrt();
}
}
}