38

In C/C++, I have a bunch of functions that I call from main(), and I want to rewrite this in C#. Can I have stand alone functions(methods) or do I have to put them in another class? I know I can have methods within the same class, but I want to have a file for each function/method.

Like this works:

using System.IO;
using System;


class Program
{
    static void Main()
    {
House balls = new House();
balls.said();

    }
}
    public class House
    {
        public void said()
        {
            Console.Write("fatty");
            Console.ReadLine();

        }
    }

But then I have to create an instance of House and call said(), when in C I can just call said().

bob packer
  • 391
  • 1
  • 3
  • 5

8 Answers8

36

For reference, I want to add the using static addition of C# 6 here.

You can now use methods of a static class without having to type the name of that class over-and-over again. An example matching the question would be:

House.cs

public static class House
{
    public static void Said()
    {
        Console.Write("fatty");
        Console.ReadLine();
    }
}

Program.cs

using static House;

class Program
{
    static void Main()
    {
        Said();
    }
}
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
  • Finally, something I've wanted for a long time but missed this concept. – JWP Jul 05 '21 at 19:45
  • 2
    @JWP meanwhile C# 9 has arrived which added 'top-level-statements' which might also be interesting. See [the MS docs](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements). – huysentruitw Jul 06 '21 at 09:43
  • They have global using directives now https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#global-using-directives/. Which means we can create a separate GlobalUsings.cs file and specify `global using static House;` and the methods from this class will be available anywhere in the solution. – Serj Dec 18 '22 at 04:48
22

No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.

Donnie
  • 45,732
  • 10
  • 64
  • 86
12

If using C# 9 it is now kinda possible, thanks to the top-level statements feature.

In your executable project, the following syntax is now allowed:

using SomeNamespace;

// The following statements are seemingly defined without even a method,
// but will be placed inside a "Main" static method in a "$Program" static class
SayHello();
var classFromSomeNamespace = new SomeClass(); // from SomeNamespace
classFromSomeNamespace.SomeMethod();

// This function is seemingly defined without a class,
// but on compile time it will end up inside a "$Program" static class
void SayHello()
{
    Console.WriteLine("Hello!");
}

// Here the "traditional" syntax may start
namespace SomeNamespace
{
    public class SomeClass
    {
        public void SomeMethod()
        {
            Console.WriteLine("SomeMethod called");
        }
    }
}

It should be noted, that the above syntax is valid only for a single file in a project, and the compiler actually still wraps this all inside a $Program static class with static methods. This feature was introduced specifically to avoid boilerplate code for the program entry point, and make it possible to easily write "scripts" in C#, while retaining the full .NET capabilities.

Evengard
  • 608
  • 9
  • 19
8

There is no concept of standalone functions in C#. Everything is an object.

You can create static methods on some utility class, and call those without creating an instance of a class eg

class Program
{
    static void Main()
    {
    House.said();
    }
}

public class House
    {
        public static void said()
        {
            Console.Write("fatty");
            Console.ReadLine();

        }
    }
Winston Smith
  • 21,585
  • 10
  • 60
  • 75
6

You have to put them in a class, but the class can be static as others mentioned. If you REALLY want to have a separate file for each method, you can mark the class as partial to get the following:

Program.cs
----------
class Program
{
    static void Main()
    {
        House.said();
        House.saidAgain();
    }
}

House-said.cs
-------------
public static partial class House
{
    public static void said()
    {
        Console.Write("fatty");
        Console.ReadLine();
    }
}

House-saidAgain.cs
------------------
public static partial class House
{
    public static void saidAgain()
    {
        Console.Write("fattyAgain");
        Console.ReadLine();
    }
}

I wouldn't recommend separating each one out, however. Partial classes are mostly used so that designer-generated code won't overwrite any custom code in the same class. Otherwise you can easily end up with hundreds of files and no easy way to move from one method to another. If you think you need a partial class because the number of methods is getting unmaintainable, then you probably need to separate the logic into another class instead.

Nelson Rothermel
  • 9,436
  • 8
  • 62
  • 81
4

Although the concept of stand-alone functions exists in .NET, C# doesn't allow you to specify such functions. You need to stick them inside a static Utils class or similar.

thecoop
  • 45,220
  • 19
  • 132
  • 189
2

If you declare your method as static (that is: public static void said()) then you can just call it with House.said(), which is as close as you'll get in C#.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
1

You could add all your methods to the Program class, but this would quickly become an unmaintainable mess, commonly referred to as the God Class or Ball of Mud anti-pattern.

Maintaining a single file for each function would similarly become a huge mess. The questions "Where do I put my methods" and "What classes should I create" are answered by Design Patterns. Classes aggregate behavior (functions) and should do one thing (Single Reponsibility.)

Dave Swersky
  • 34,502
  • 9
  • 78
  • 118
  • 1
    yea, specifically looking to avoid the God Class. – bob packer Oct 12 '10 at 16:18
  • 1
    Create classes for doing things (actors, builders) and carrying data (Data Transfer Objects.) Don't be afraid to have many classes, as this (to a point) is an indication of good Separation of Concerns. Open-source projects in C# are a good source of guidance for how to organize classes and methods. – Dave Swersky Oct 12 '10 at 16:21