Creating custom classes and methods in C#

0
749
Creating custom classes and methods in C#

In C#, a class is a blueprint for an object that can contain data (also known as “fields”) and behaviour (also known as “methods”). You can create your own custom classes to represent real-world objects or abstract concepts, and define methods to specify the behaviour of your objects.

Here is an example of a simple C# class:

public class MyClass
{
    // Fields
    public int field1;
    public string field2;

    // Methods
    public void Method1()
    {
        // Method code goes here
    }

    public int Method2(int param1)
    {
        // Method code goes here
        return 0;
    }
}

In this example, the class is called “MyClass” and it has two fields (field1 and field2) and two methods (Method1 and Method2). The fields are variables that can hold data, and the methods are functions that can perform actions.

Might be interesting: How to Enable and Disable Windows Updates

To create an instance of a class, also known as an “object,” you can use the new keyword and call the class’s constructor:

MyClass myObject = new MyClass();

Once you have an object, you can access its fields and methods using the dot operator (.). For example:

myObject.field1 = 10;
int result = myObject.Method2(5);

In addition to creating custom classes, you can also define your own methods within an existing class. To do this, you simply need to specify the return type, the method name, and any parameters that the method takes. Here is an example of a method definition within a class:

public int Multiply(int num1, int num2)
{
    return num1 * num2;
}

You can then call this method on an object of the class like this:

int result = myObject.Multiply(10, 20);

Defining custom classes and methods is an important part of object-oriented programming, and is a key feature of the C# language. In future lessons, we will explore these concepts in more detail, including how to create and use constructors, how to overload methods, and how to use inheritance to create more complex and powerful classes.