I want to make my program "modular" and I'm wondering if I'm taking the right approach to this.
What I mean by this is I want to have some reusable "processing" stuff contained within it's own c# files. In this way, I could simply copy the files between projects to be able to reuse my code. Since this probably doesn't make sense, let me explain with an example.
Program.cs
static class Program
{
static void Main()
{
int[] x = {0, 0, 0, 0, 0};
BClass b = new BClass(x);
Console.Write("[ ");
foreach (int i in x)
{
Console.Write(i + " ");
}
Console.Write("]\n");
Console.Read();
}
}
BClass.cs
class BClass
{
int[] x;
public BClass(int[] x)
{
for (int i = 1; i < 5; i++)
{
x[i] = i;
}
}
}
Now, this works fine, I get the output I would expect, but it feels wrong, I guess? In addition to my gut feeling, I am getting warnings (as I would expect) because the BClass
object is unused. Ultimately, my question is What is the best way to make a program modular like this? Using a class feels wrong because I end up with a reference to an object that will never be used. Perhaps I'm using the class wrong?
It looks like you want to have some logic that you can run from anywhere in your application. For that, you'd use a static method.
A Static method requires no instance to run.
Since all BClass
does is contain a static method, you might as well make BClass
static too. A static class is a class that cannot be instantiated. It only exists to contain static methods.
public static class BClass
{
public static void DoStuff(int[] x)
{
for (int i = 1; i < 5; i++)
{
x[i] = i;
}
}
}
And when you want to use this logic, you simply do this
BClass.DoStuff(myArray);