Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can there be stand alone functions in C# without a Class?

Tags:

c#

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().

like image 932
bob packer Avatar asked Oct 12 '10 16:10

bob packer


People also ask

What are standalone functions?

A standalone function is a function (a subprogram that returns a single value) that is stored in the database. Note: A standalone function that you create with the CREATE FUNCTION statement differs from a function that you declare and define in a PL/SQL block or package.

What is freestanding function?

A stand-alone function is just a normal function that is not a member of any class and is in a global namespace. For example, this is a member function: class SomeClass { public: SomeClass add( SomeClass other ); }; SomeClass::add( SomeClass other ) { <...> }

Does C++ support stand-alone functions?

There are two types of functions in C++: stand-alone functions and member functions.

How many functions can be called in a single program?

3) There is no limit on number of functions; A C program can have any number of functions.


2 Answers

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();     } } 
like image 62
huysentruitw Avatar answered Sep 19 '22 13:09

huysentruitw


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

like image 42
Donnie Avatar answered Sep 20 '22 13:09

Donnie