static void C# method: (lesson on methods)

Advertisements

Hello everyone,

Michael here, and in today’s post, we’re going to build upon what we learned in the previous post on C# classes and objects-new C# class.

In this post, we’ll use the same base code as we did in the previous post, but we’re going to build upon what we’ve learned by adding methods into the classes we’ve built!

What is a C# method?

Before we actually get into the method-making, as a quick refresher, what is a method? In programming, a method is a set of instructions for a program to execute when the method is called in the script.

static void C# method

With that quick refresher, let’s dive right in to creating C# methods. We’ll add our methods to the https://github.com/mfletcher2021/blogcode/blob/main/Cat.cs script we developed in the previous post.

First off, let’s explore a simple static void () method.

static void meow()
{
   Console.WriteLine("meowmeowmeowmeow");
}

In this simple method, I’m telling the console to output the line "meowmeowmeowmeow" every time this method is called.

Now why is it a static void method? static indicates that this method belongs to the Cat class while void indicates that this method doesn’t have a return type.

static void Main()

Yes, as you may have noticed, the Main() method in C# is also a static void method. Why might that be? The Main() method acts as an entry point to execute the program; this method sets variables and executes all the method calls for running the script. Since the Main() method doesn’t return anything, static void() would be the most appropriate type to use for this method.

meow();

So, how do we call the method? Here’s how:

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void meow()
    {
        Console.WriteLine("meowmeowmeowmeow");
    }

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);
        meow();
        meow();

    }
}

11
meowmeowmeowmeow
meowmeowmeowmeow

In the Main() method, simply write the name of the method followed by a semicolon-meow(); in this case. Yes, you can call the method as many times as you want in the Main() method-I did call meow(); twice indicating that there’s a very meowy orange cat.

calculateHumanAge(with parameters)

Now that I’ve shown you how to create a basic method, let’s try something a bit more advanced. This time, let’s see how we can create a method with parameters:

static void calculateHumanAge(int age)
    {
        Console.WriteLine("The cat is " + age * 7 + " in human years.");
    }

In the calculateHumanAge method, I pass in a parameter-int age and output a line that says The cat is (age*7) in human years, which multiplies the number I used in the method by 7.

  • Notice how the method type is still void-this is because we’re not returning anything from the method (Console.WriteLine() isn’t considered a return value). More on return values later.
  • Methods can have as many parameters as you want, but you’ll need to remember to include all of them whenever you call the method. You’ll also need to include value types for each parameter (e.g. string, int and so on).

Let’s try it out in our code!

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void meow()
    {
        Console.WriteLine("meowmeowmeowmeow");
    }

    static void calculateHumanAge(int age)
    {
        Console.WriteLine("The cat is " + age * 7 + " in human years.");
    }

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);
        meow();
        meow();
        calculateHumanAge(11);

    }
}

11
meowmeowmeowmeow
meowmeowmeowmeow
The cat is 77 in human years.

When I call the calculateHumanAge method in the Main method and pass in 11 as a parameter, I get the output The cat is 77 in human years., indicating that the method did multiply the integer parameter by 7 before outputting that string.

string nameBackwards (return something)

Last but not least, let’s examine method return values.

static String nameBackwards(string name)
    {
        char[] nameList = name.ToCharArray();
        String reversedName = String.Empty;

        for (int i = nameList.Length - 1; i >= 0; i--)
        {
            reversedName += nameList[i];
        }

        return reversedName;
    }

In the nameBackwards method, we’ll take a String parameter and return that same string printed backwards. We will accomplish this by first creating a character array consisting of each character in the name string, then creating a reversedName string by essentially writing each character in the nameList array in reverse order. We will then return the reversedName string in the method.

  • Yes, C# has a pretty unusual method to initialize empty strings. Instead of doing something like testString = '' like you would do in Python, you would write something like String testString = String.Empty (special emphasis on the String.Empty part).

Let’s see the output!

class Cat
{
    string color = "orange";
    int age = 11;
    string gender = "male";

    static void meow()
    {
        Console.WriteLine("meowmeowmeowmeow");
    }

    static void calculateHumanAge(int age)
    {
        Console.WriteLine("The cat is " + age * 7 + " in human years.");
    }
    
    static String nameBackwards(string name)
    {
        char[] nameList = name.ToCharArray();
        String reversedName = String.Empty;

        for (int i = nameList.Length - 1; i >= 0; i--)
        {
            reversedName += nameList[i];
        }

        return reversedName;
    }

    static void Main(string[] args)
    {
        Cat orangeCat = new Cat();
        Console.WriteLine(orangeCat.age);
        meow();
        meow();
        calculateHumanAge(11);
        Console.WriteLine(nameBackwards("Simba"));

    }
}

11
meowmeowmeowmeow
meowmeowmeowmeow
The cat is 77 in human years.
abmiS

In this example, I passed in the string Simba as the parameter for the nameBackwards method and got the backwards string abmiS as the return value-yes, the nameBackwards method will keep the upper-and-lower-casing of the original input string intact.

  • Since I didn’t see the output when simply writing nameBackwards("Simba"), I wrapped this method call inside a Console.WriteLine() method call to see the output.

Today’s script can be found on my GitHub at the following link-https://github.com/mfletcher2021/blogcode/blob/main/CatMethods.cs.

Thanks for reading!

Michael

Leave a ReplyCancel reply