Organizing c# code into different files - c#

I've gotten to a point where my main code file is about a thousand lines long and it's getting un-manageable; that is, I'm starting to get confused and not know where to locate some things. It's well-commented but there's just too much stuff.
I'd really like to be able to organize my code into different files, each with its own purpose. I want to get all the help VS gives me as I type when I edit these other files. A picture can say a thousand words:
alt text http://img64.imageshack.us/img64/7848/codeorganizationscreens.png
Is what I'm trying to do even possible?

Yes, but you need to be in the same namespace and declare the class just like you did in the main file, an example:
file1.cs
namespace Names
{
public partial class Hello
{
public void DoSomething() { }
}
}
file2.cs
namespace Names
{
public partial class Hello
{
public void Go() { DoSomething(); }
}
}

Although what other people say about partial classes is true. I'd also suggest you to analyze refactoring opportunities on your class.
If you're having problems to manage it, you could try to split your single class in several classes with less responsibilities.
IMHO partial classes may not help very much. Do you have your class separated in regions? Regions improve the readability of your code.

Yes you can split any partial class across as many files as you like.

Strip out each decent size class into at least one file. Wrap each class in the same namespace.
For large classes use either:
a. Region blocks eg
#region // Members
int my_int;
// other members...
#endregion
b. partial keyword to break a single class accross several files.

Related

Partial Class Winform Form

It was taught to me that any alterations to an object on a form (change the text, make visible/invisible or change the color and so on) should be done in the corresponding form class.
But due to the large amount of such alterations done inside the project, the file has became large and hard to search through. I've read online that a Partial Class could help, but there was no explanation on how to implement this. As an easy example, I have the following 2 files:
Form_Main.cs
namespace Test
{
partial class Form_Main : Form
{
public Form_Main()
{
InitializeComponent();
}
}
}
AND Form_Main.Dataloader.cs
namespace Test
{
partial class Form_Main : DataLoader
{
public void SetText()
{
TextBox_StudentSurname.Text = "1";
}
}
}
How can I make this work? Because if I do this I get several errors in the designer.
Your main problem is the first error printed: You cannot declare different base classes in different partial implementations. I don't know which of the two base classes is the right one (the one you previously used), but as always, a class cannot have two base classes. It is legal to specify the base class only in one of the parts, but if it is specified multiple times, it must be the same.

access methods from plain code files and call it in main class (like php include)

This was a general question asked by a colleague of mine....
Is it possible to "outsource" code, and then call it in the main class (e.g. Form1.cs)?
This originates from the fact that he wants to organize his amount of code better than with regions, in the main class.
My first thought was - of course it is!
Use static Extentions, reference it to the main class, and call it through this.Method().
But he meant something like the "include" pattern in PHP....
Is that even possible?
he wants to organize his amount of code better than with regions, in the main class.
You can use partial classes to split the implementation of a single class into multiple (and perhaps more manageable) source files.
In File1.cs:
public partial class MyClass {
public void F() { ... }
}
In File2.cs:
public partial class MyClass {
public void G() { ... }
}
MyClass now has two methods, F and G.
You can externalize using partial classes or decouple it using c# assembly (dll).

In C#, what is a good way to exclude a class when outputting code from textfile

What I want to do may seem like a weird scenario. Please keep in mind that I need to do this for a Demo project, where I output c# code to the user to teach them how certain controls are coded.
I am given a .cs file and I need to output the contents. There is at least one class in the file, and at most...a lot. I need to output the whole file, EXCEPT one type of class. The specific type of class that I want to prevent being outputted all inherit a certain base class, so they should be easy to distinguish.
Here is an example:
public abstract class A{}
public class B{]
public class C{}
Assume these are the base-types that some of my classes may inherit. I want to prevent outputting all classes that inherit from A. A is probably going to be the only abstract base class so if that can help in anyway, that would be awesome.
Let's say I'm given a file, example.cs:
using System;
using OtherStuff;
namespace blah.blahagain.someotherblah
{
[AttributeOne]
[AttributeTwo]
[AttributeThree]
public class AA: A
{
//stuff
}
public class BB: B
{
//stuff
}
public class CC: C
{
//stuff
}
public class D
{
//stuff
}
}
And the output should be
using System;
using OtherStuff;
namespace blah.blahagain.someotherblah
{
public class BB: B
{
//stuff
}
public class CC: C
{
//stuff
}
public class D
{
//stuff
}
}
The only way I have thought of is brute-force string manipulation. I can't, however, use whitespace as a separator between classes because there is no guarantee if there will even be white space between classes. I will need to keep track of open and closed curly brackets to discover where one class begins and another end. I also need to test for the base class of each class by testing the string tokens before the first {} pair.
Also I need to prevent the attributes of AA from outputted too.
Since there are many brighter minds out there, I am here to ask if there is another simpler/cleaner method for doing what I need.
Thanks for reading!
Edit after YetAnotherUser's answer: The output should be exactly the same as the file, which includes all comments.
Another edit: Instead of answering with certain software or libraries that could do this, I would more prefer algorithms. Maybe regular expressions? I am not good with them so I do not know the extend that they can be used for.
Could you wrap everything you need to exclude with:
#region ExcludeRegion
[AttributeOne]
[AttributeTwo]
[AttributeThree]
public class AA: A
{
//stuff
}
#endregion
See the #region documentation
This should be relatively easy to scan for and exclude. It also gives you the added benefit of showing what you're hiding in the IDE.
You can try to use open-source lib NRefactory. It supports parsing the code into AST which you can modify afterwards and generate output code. It also can retain your comments as shown on their wiki page.
Found it here: An alternative for "CSharpCodeProvider.Parse"
Update: Apparently there's no implementation of CodeDomProvider that supports parsing. Hence this is invalid - I'll keep this post to ensure this is highlighted to someone thinking on same lines.
You can parse the code using CodeDomProvider and then remove the required classes and regenerate the code file.
If it is for educational purpose, this might not exactly fit your needs as generated file might not exactly match with the original source file.
See -
System.CodeDom Namespace
Using the CodeDOM
Microsoft .NET CodeDom Technology - Part 1

naming folders in nested classes

If we have the following situation:
namespace SomeNameSpace
{
public class Class1
{
private class NestedClass1
{
// NestedClass1 implementation
}
private class NestedClass2
{
// NestedClass1 implementation
}
}
public class Class2
{
// so on ...
}
}
What is the best way to organize folders and files for nested classes?
First of all, we have Folder "SomeNameSpace".
Then files "Class1.cs, Class2.cs, ...".
Consider nestes classes in "Class1".
Is it the right way to create files "Class1.NestedClass1.cs, ..." and place them in folder SomeNameSpace?
Or create new folder, then what name should it have, and may be it is not proper way because it looks like new namespace?
In general nested classes are somehow considered bad practice, but sometimes you do need them. Implementing a state pattern often is much easier if the states are nested classes that can access private methods of their context.
I tend to create separate files like Class.Subclass.cs if I have more than one nested class or one nested class that clutters the code of its parent class. In this case of course Class has to be declared partial.
Nevertheless this is just my personal opinion, do it as you/your team like it best.
Given your example, personally I would name them accordingly:
Class1.cs
Class1.NestedClass1.cs
Class1.NestedClass2.cs
Class2.cs

C# share code between classes

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda

Categories

Resources