Class Methods

Lesson 27
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, a class method is a function that is defined within a class and can be called on instances of that class. These methods can be used to perform actions on the data stored within the class, or to return data based on the state of the class.

Here’s an example of a class method in C#:

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }

    public void SayHello() {
        Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old.");
    }
}

In this example, we have a class called Person that has two properties, Name and Age. We’ve also defined a method called SayHello that simply prints out a message that includes the person’s name and age.

To call this method, we first need to create an instance of the Person class:

Person john = new Person();
john.Name = "John";
john.Age = 30;

Now that we have an instance of the Person class, we can call the SayHello method on it:

john.SayHello(); // Output: "Hello, my name is John and I am 30 years old."

Notice how we’re calling the SayHello method on the john object, which is an instance of the Person class. This is what allows us to use the data stored within the object (in this case, the person’s name and age) to execute the method.

Class methods can be used to perform a wide variety of actions, from simple operations like printing out a message to complex calculations and data transformations. They are a powerful tool for organizing and working with code in object-oriented programming.