Classes
Adding methods to a class
Now we know how to define a class and create an instance of it, we need to see how we can extend the methods capabilities. We're going to use a syntax like the following example:
using System;
public class Person
{
public string GetFullName()
{
return "John Smith";
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}
In the above example, we've extended our Person class with some additional functionality. In this instance, we've added a method called GetName which allows us to return a string variable. You've met methods before:
public class Program
{
public static void Main()
{
}
}
The Main method of your program is like our GetName method, they both belong to a class ( Program or Person ), the big difference between them, is the Main method returns void and our GetName method returns a string . void is a special keyword which essentially means 'nothing'. Let's see how we can declare a method.
Starting with our blank Person class:
public class Person
{
}
We need to add some code within the { and } braces. Let's add the following and see what it means:
public string GetFullName()
{
}
In our method declaration, we're telling the compiler that we want a method named GetFullName , which returns string . The parenthesis characters ( and ) would allow us to provide arguments, but we're not going to do that right now. Again, we also use the public keyword to tell the compiler that this will be a method that can be externally called. We also require some additional braces { and } to mark the boundary of the method body.
Putting that together, we get the following:
public class Person
{
public string GetFullName()
{
}
}
But this won't compile yet! The reason being is that in our declaration of our method, we've stated that it should return a string value, but we haven't provided one. Let's fix that by adding the following line within the GetFullName method:
return "John Smith";
If the method should not return anything, then you can use the return type void. void is a special keyword in C# that basically says "I don't return anything". Here is an example of a void method:
public void WriteName()
{
Console.WriteLine("John Smith");
}
You've previously met the void keyword in our Program class:
public class Program
{
public static void Main()
{
}
}
So with that now added we can compile our code.