In C# there are no functions like in C/C++, because it uses a very pure object oriented approach. Almost everything you do exists within a class (or a struct) that represents an object that has parts (Members, like 'variables') and actions (or Methods, like 'functions').
An object uses the Methods and Members of its class to interact with another class. A good way to look at it is this:
I am a Person object, and I have a name and age (my 'Members') and I can do actions such as eat or punch other Person objects (these actions would be my Methods).
Some example in code:
Code:
public class Person
{
// My 'members'
public string Name;
public int Age;
// My 'methods'
public void Punch(Person personToPunch)
{
... code here...
}
}
Beautiful language isn't it?
Now you could consider the method above as a function (though technically it's not). And this is a very good way of representing 'objects' that can do things to other objects.
But if I just have a simple function that calculates 2*2 and prints the results, this is how we would have to do it:
Code:
public class SimpleMaths
{
public void Calculate()
{
Console.WriteLine(2*2);
}
}
public class Program
{
public static void Main()
{
// Create a new instance of our
// SimpleMaths object
SimpleMaths mySimpleMaths = new SimpleMaths();
// Call the SimpleMaths method
mySimpleMaths.Calculate();
}
}
Its not all that usable, first we have to create an instance of our object, then call the method. The real problem is we have to go around creating instances of a class whenever we want to use one of its methods.
But notice how we used Console.WriteLine() in the above example? Did you know Console is a class? Scandalous! Why can they do it when we can't?
The answer is in static methods. A static method has the keyword 'static' in front of it, and does not require an instance of the object to be called. Heres how the .NET Frameworks Console class would look (very simply):
Code:
public class Console
{
[....]
// Note the 'static'
public static void WriteLine(string stuffToWrite)
{
// Do stuff...
}
[....]
}
By using static methods you can create what C++ might consider a "global function", a method that is avaliable to any other class. You can also create global variables using static properties:
Code:
public class Console
{
[....]
// Note the 'static'
public static string GlobalVariable;
public string NonGlobalVariable;
[....]
}
Often you will have a few "global functions" that you use a lot in your applications. A good way to keep them all together is to create a class called something like "Globals" or "Utilities" to store any common static methods.
In summary, everything must exist in a class in C#. And every time you use a property or method, you need an instance of that class, unless the method/property is marked static.
Hope that answered your question