Classes With Static and Non-Static Methods in C#
Firstly, we will cover the difference between static and non-static methods and then move further.
Static Methods in C#
A static method belongs to the class, not the object (instance of the class), or we can say that "A static method is a method that belongs to a class rather than an instance of a class." This is the whole simple definition, and it is a very simple one, but it requires knowledge and explanation so that we will see our first example.
public partial class Taxpayer
{
public string UniqueIdentificationNumber { get; set; }
public string Password { get; set; }
public bool CheckUIN()
{
var regex = new Regex(@"^\w+$");
var match = regex.Match(UniqueIdentificationNumber);
return match.Success;
}
public static bool CheckPassword(string password)
{
return password.Any(c => char.IsUpper(c))
&& password.Any(c => char.IsLower(c))
&& password.Any(c => char.IsNumber(c));
}
public bool CheckTaxpayer()
{
return CheckUIN() && CheckPassword(Password);
}
}
In the above example, there is the Taxpayer class; this class contains two properties named as UniqueIdentificationNumber and Password; besides these properties, there are three methods also one is for checking the UIN number (Unique Identification Number), the second one is for checking password and the last one is for checking the whole Taxpayer object.
Methods CheckUIN and CheckTaxpayer are known as instance class methods, and on the other hand, the CheckPassword method is static. The Taxpayer instance calls the first two to access both properties because properties are also part of the Taxpayer instance. Still, the CheckPassword can't access the properties because it belongs to the Taxpayer type, not the instance, so in that case, we need to provide the value as a parameter.
var taxpayer = new Taxpayer()
{
UniqueIdentificationNumber = "AGAPO897P",
Password = "ThisIs3asyPa$$word"
};
Console.WriteLine($"Unique Identifire Number is correct: {taxpayer.CheckUIN()}");
Console.WriteLine($"Password is correct: {Taxpayer.CheckPassword(taxpayer.Password)}");
Console.WriteLine($"Whole object is correct: {taxpayer.CheckTaxpayer()}");
The CheckEmail() and CheckTaxpayer() methods are used as we are used to, as a method on the Taxpayer object. But the CheckPassword() method can't be accessed as a typical method on an object. Remember, it does not exist on an object but on a type Taxpayer, so we need to use the type and write Taxpayer.CheckPassword(). This method also expects a parameter, and we need to provide one. Because we are interested in the taxpayer's password, we provide taxpayer.Password as a parameter.

Join the conversation! Your thoughts help the community grow.