Search code examples
c#classmethodsorganization

Is it possible to spread out a C# class in multiple .cs files like in c++?


In C++, you can define parts of a class in seperate cpp files. So for example,

Header:

// Header.h
class Example
{
public: 
    bool Func1();
    bool Func2();
};

CPP 1

//Func1.cpp
#include "Header.h"
bool Example::Func1()
{
    return true;
}

CPP 2

//Func2.cpp
#include "Header.h"
bool Example::Func2()
{
    return false;
}

Is it possible in C# to do something similar? I'm making server and client classes, and there are some methods that will never be modified (Ex. SendString, GetString, SendInt, GetInt, etc.) and I would like to seperate them from methods that will be actively updated depending on what type of packets are being received.

Is there any way to organize the code like i'm trying to do, or do I just need to make another class to hold all of the methods that will not be further modified?


Solution

  • Partial class is approach - generally used for splitting auto-generated and user-authored code. See When is it appropriate to use C# partial classes? for cases when using it makes sense.

    It may be better to refactor code to keep classes in single file as it is significantly more common for C# source.

    One option is to use extension methods over small interface and put separate closely grouped methods into separate static classes.

     // Sender.cs
     // shared functionality with narrow API, consider interface
     class Sender
     {
         public SendByte(byte byte);
     }
    
     // SenderExtensions.cs
     // extensions to send various types 
     static class SenderExtensions
     {
         public static SendShort(this Sender sender, uint value)
         {
            sender.SendByte(value & 0xff);
            sender.SendByte(value & 0xff00);
         }
     }