-1

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?

  • 10
    [Partial class](https://msdn.microsoft.com/en-us/library/wa80x488.aspx) – DrewJordan Sep 09 '15 at 18:04
  • 1
    @DrewJordan You can kindly post it as an answer to be useful for other users, many users don't read comments to find answer :) – Reza Aghaei Sep 09 '15 at 18:07
  • 1
    http://stackoverflow.com/questions/3601901/why-use-partial-classes – xxbbcc Sep 09 '15 at 18:08
  • Change your question more to what you had tried in c#, than showing what you have in c++! And probably remove the c++ tag, we (_"The c++ shark tank"_) don't like it! – πάντα ῥεῖ Sep 09 '15 at 18:11
  • 2
    @πάντα ῥεῖ "You're dead to me." - Shark tank voice. –  Sep 09 '15 at 19:28
  • @JacobPreston I've also got _laser beams_ ;-) ... _""You're dead to me."_ Why bother so much about pro tips? I didn't gave any downvotes or such. I just pointed out your question isn't primarily about c++ code, but the tag requires it. Much like the c/c++ tag combo failure. – πάντα ῥεῖ Sep 09 '15 at 19:31
  • @JacobPreston Not to mention your obvious lack of research, no matter what language in particular! – πάντα ῥεῖ Sep 09 '15 at 19:40

2 Answers2

10

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);
     }
 }
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

Yes we can do similar thing in C#. We have partial class in C#.