C#/C# Tutorial

C# How to Create Classes And Objects | C# Tutorial for Beginners

DragonTory 2023. 3. 4. 21:46
반응형

C# How to Create Classes And Objects | C# Tutorial for Beginners

 

In C#, a class is a blueprint or a template for creating objects. An object is an instance of a class. Classes in C# define the properties and behaviors of the objects that will be created from them.

 

Class members

 

Class members are the variables, properties, methods, events, and other elements defined within the class. 

Here are some examples of class members:

 

1. Fields:

Fields are variables that are declared within the class and hold data values. Fields can be private or public and can have various data types.

public class Person
{
    private string _name;
    public int Age;
}

 

2. Properties:

Properties provide a way to read or write the values of a field while controlling the access to that field. Properties have a get and/or set accessor and can be used to validate or transform data.

public class Person
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

 

3. Methods:

Methods are functions that are defined within the class and can be called to perform some action. Methods can have parameters and return values.

public class Person
{
    public void SayHello()
    {
        Console.WriteLine("Hello!");
    }

    public void SayName(string name)
    {
        Console.WriteLine($"My name is {name}.");
    }
}

 

4. Constructors:

 Constructors are special methods that are used to create and initialize objects of the class. Constructors can have parameters to accept values that are used to initialize the object.

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

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

 

5. Events:

 Events provide a way to raise notifications when something happens within the class. Events are typically defined as a delegate type and can be subscribed to by other objects to receive notifications.

public class Button
{
    public event EventHandler Click;

    protected virtual void OnClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}

 

Here is an example of a class in C# that includes variables, properties, methods, and events:

using System;

public class Person
{
    // private field
    private string _name;

    // public property with get and set accessors
    public string Name
    {
        get { return _name; }
        set
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("Name cannot be empty.");
            }
            _name = value;
        }
    }

    // private field
    private int _age;

    // public property with get and set accessors
    public int Age
    {
        get { return _age; }
        set
        {
            if (value < 0 || value > 120)
            {
                throw new ArgumentException("Age must be between 0 and 120.");
            }
            _age = value;
        }
    }

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

    // public event
    public event EventHandler AgeChanged;

    // private method to raise the AgeChanged event
    private void OnAgeChanged()
    {
        AgeChanged?.Invoke(this, EventArgs.Empty);
    }
}

In this example, the Person class has two private fields _name and _age, and two public properties Name and Age with get and set accessors. The properties perform some validation on the input values before setting the private fields.

The class also has a public method SayHello() that writes a message to the console using the values of the Name and Age properties.

Additionally, the class has a public event AgeChanged that is declared using the event keyword and the EventHandler delegate type. The AgeChanged event is raised by a private method OnAgeChanged() that invokes the event with the this keyword and an empty EventArgs object.

This example demonstrates how to use variables, properties, methods, and events in a class to create a simple object with encapsulated data and behavior.

 

Access Modifiers

Access modifiers control the visibility and accessibility of class members, such as fields, properties, methods, constructors, and nested types.

Here are the access modifiers available in C#:

1. public: 

The public modifier makes a member accessible from anywhere in the code, including from other assemblies.

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

 

2. private:

The private modifier makes a member accessible only from within the class that defines it. This is the default access modifier for class members.

public class Person
{
    private string _secret;

    public void DoSomething()
    {
        _secret = "This is a secret.";
    }
}

 

3. protected: 

The protected modifier makes a member accessible from within the class that defines it and from derived classes.

public class Animal
{
    protected string _name;

    public Animal(string name)
    {
        _name = name;
    }
}

public class Cat : Animal
{
    public Cat(string name) : base(name)
    {
        // _name is accessible from derived class
        Console.WriteLine($"My name is {_name}.");
    }
}

 

4. internal: 

The internal modifier makes a member accessible only from within the same assembly.

internal class MyClass
{
    // internal class
}

public class MyPublicClass
{
    internal MyClass MyInternalClass { get; set; }
}

 

Creating a Class

To create a class in C#, use the class keyword followed by the class name. Here's an example of a simple class definition:

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

This defines a class named Person with two properties: Name and Age. 

The public access modifier makes these properties accessible from outside the class.

 

Creating an Object

To create an object of a class, you use the new keyword followed by the class name and any necessary arguments. Here's an example of creating a Person object:

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

This creates a new Person object and sets its Name and Age properties.

 

Constructors

Constructors are special methods that are called when an object is created. They are used to initialize the object's properties and perform any other necessary setup. 

Here's an example of a Person class with a constructor:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

This defines a Person class with a constructor that takes a name and an age parameter. The constructor sets the object's Name and Age properties using the values passed in.

 

Distructors

 

A destructor is a special method that is called when an object is being destroyed, typically when it goes out of scope or when it is explicitly destroyed using the Dispose() method. The destructor has the same name as the class but is preceded by a tilde ~.

Here is an example of a destructor:

public class MyClass
{
    public MyClass()
    {
        // constructor
    }

    ~MyClass()
    {
        // destructor
    }
}

 

The destructor is automatically called by the garbage collector when the object is no longer needed. The purpose of the destructor is to perform any necessary cleanup or resource deallocation before the object is destroyed. 

For example, if the object holds unmanaged resources such as file handles, network connections, or database connections, the destructor can release these resources to prevent memory leaks or other problems.

Note that the destructor cannot be called directly by the code and cannot be overloaded with parameters or access modifiers. 

Also, the use of destructors is generally discouraged in C# because the garbage collector automatically manages the memory and resource cleanup for most objects

Instead, it is recommended to use the Dispose() method and the using statement to explicitly release unmanaged resources and manage the lifecycle of disposable objects.

 

Methods

Methods are functions that can be called on an object. They are defined within a class and can access the object's properties. 

Here's an example of a Person class with a method:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    public void SayHello()
    {
        Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
    }
}

This defines a SayHello() method that prints a greeting with the object's Name and Age properties.

 

You can call this method on a Person object like this:

Person person = new Person("John", 30);
person.SayHello();

This will output:

Hello, my name is John and I am 30 years old.

 

These are the basic concepts of C# classes.

반응형