I am assuming your main goal was to distribute the methods amongst different namespaces, otherwise it would have been trivial (put everything in one class whether partial or not and you're done).
So the assumed objectives are:
- Have the 2 methods
Bar1
in namespace name1
and Bar2
in namespace name1.name2
- Be able to invoke any of the above methods in the context of one class, here
ClsFoo
You can't achieve this with partial classes, but you can achieve it in a different way: if you use extension methods and bind them to a particular class, here ClsFoo
, then you can do the following:
using SomeOtherNamespace;
using name1;
using name1.name2;
namespace mainClass
{
public static class mainClass
{
public static void Main()
{
var classFoo = new ClsFoo();
var count = classFoo.Bar1() + classFoo.Bar2();
Console.WriteLine($"count = {count}"); // output is 110
} // main
} // class
} // namespace
namespace SomeOtherNamespace
{
public class ClsFoo
{
// does not need to contain any code
} // class
} // namespace
namespace name1
{
public static class FooExt
{
public static int Bar1(this ClsFoo foo)
{
return 10;
} // method
} // class
} // namespace
namespace name1.name2
{
public static class FooExt
{
public static int Bar2(this ClsFoo foo)
{
return 100;
} // method
} // class
} // namespace
Run it online
This way, you declare an empty class ClsFoo
and then write some extension methods Bar1()
and Bar2()
, which reside in different namespaces and static extension classes.
Note: The extension classes may have the same name FooExt
as long as they are in different namespaces, of course you can also give them different names like FooExt1
and FooExt2
if you like - and the example will still work; even in older versions of C#.