How do I create a method in a class to delete the class instance?

48 Views Asked by At

I have created an employee class, and after creating an object of the employee class you can set it with details such as: age and date of birth. A validate method in the class checks if the age conforms with the date of birth, if not the employee instance is to be deleted.

I created a class method that prints on screen that the instance is deleted, but I actually want the method to delete the instance for real.

2

There are 2 best solutions below

0
JonasH On

You cannot delete an instance in c#, you can only remove any active references to it and let the GC do its job.

What you can do is split construction and validation into separate steps using the builder pattern. It might look something like this:

public class EmployeeBuilder
{
    private int age;
    public void SetAge(int age) => this.age = age;

    public Employee? ValidateAndCreate()
    {
        if (age < 20) return null;
        return new Employee(age);
    }
}

public class Employee
{
    public int Age {get;}
    public Employee(int age) => Age = age;
}

You might also want to take a look at the Fluent builder pattern for a variation of the same idea.

0
Jérôme FLAMEN On

Depending on your need, you can use a soft delete pattern. Add a IsDelete properties on your object.

But as already said by JonasH, it's better to not build an object if it's not valid!