You are on page 1of 2

using System;

namespace SafeLockExample
{
class SafeLock
{
private bool _locked;
private int _password;
private int _maxAttempts;
private int _remainingAttempts;

public bool Locked


{
get { return _locked; }
}

public SafeLock(int password, int maxAttempts = 3)


{
_password = password;
_maxAttempts = maxAttempts;
_remainingAttempts = maxAttempts;
_locked = true;
}

public bool Unlock(int password)


{
if (_locked)
{
if (password == _password)
{
Console.WriteLine("The lock has been successfully unlocked.");
_locked = false;
_remainingAttempts = _maxAttempts;
return true;
}
else
{
_remainingAttempts--;
Console.WriteLine($"Incorrect password. {_remainingAttempts}
attempts remaining.");
if (_remainingAttempts == 0)
{
Console.WriteLine("Too many incorrect attempts. Locking the
safe.");
Lock();
}
}
}
else
{
Console.WriteLine("The lock is already unlocked.");
}
return false;
}

public void Lock()


{
_locked = true;
}
}
}
This implementation includes the following additional features:

The maximum number of attempts to unlock the lock can be specified in the
constructor.
After a certain number of incorrect attempts, the lock automatically re-locks
itself.
The number of remaining attempts is displayed after each unsuccessful attempt.
The Locked property is read-only and can be used to check if the lock is currently
locked.

You might also like