0
0
C Sharp (C#)programming~5 mins

Property validation logic in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Property validation logic helps check if the values given to an object are correct. It stops wrong data from being saved.

When you want to make sure a user's age is not negative.
When you need to check if a name is not empty before saving.
When you want to limit a score to a certain range.
When you want to prevent invalid data from breaking your program.
When you want to give clear errors if data is wrong.
Syntax
C Sharp (C#)
private int _age;
public int Age
{
    get { return _age; }
    set
    {
        if (value < 0)
            throw new ArgumentException("Age cannot be negative");
        _age = value;
    }
}

The get part reads the value.

The set part checks the value before saving it.

Examples
This example checks that the name is not empty or just spaces.
C Sharp (C#)
private string _name;
public string Name
{
    get => _name;
    set
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException("Name cannot be empty");
        _name = value;
    }
}
This example uses a short form to check if score is between 0 and 100.
C Sharp (C#)
private int _score;
public int Score
{
    get => _score;
    set => _score = (value >= 0 && value <= 100) ? value : throw new ArgumentOutOfRangeException("Score must be 0-100");
}
Sample Program

This program tries to set a valid age first, then tries an invalid age. It catches and shows the error message.

C Sharp (C#)
using System;

class Person
{
    private int _age;
    public int Age
    {
        get => _age;
        set
        {
            if (value < 0)
                throw new ArgumentException("Age cannot be negative");
            _age = value;
        }
    }
}

class Program
{
    static void Main()
    {
        var p = new Person();
        try
        {
            p.Age = 25;
            Console.WriteLine($"Age set to: {p.Age}");
            p.Age = -5; // This will cause error
        }
        catch (ArgumentException e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}
OutputSuccess
Important Notes

Always validate data to keep your program safe and correct.

Throwing exceptions helps you find errors early.

You can also use other ways like returning error codes, but exceptions are common in C#.

Summary

Property validation checks values before saving them.

Use get and set to control property access.

Throw exceptions to stop wrong data and show clear errors.