Properties a short explanation using C#

What Are Properties?

  • Properties are methods that protect access to class members.
  • Properties are class members that provide access to elements of an object or class.
  • Protect access to the state of object.
  •  It likes fields, but they operate much like methods.
  • The get and set statements are called accessors.
  • Fields can’t be used in Interfaces so properties are the solution.

Syntax:

        private double balance;
        public double Balance
        {
            get
            {
                return balance;
            }
            set
            {
                balance = value;
            }
        }

Example:

    public class Employee
    {
        private double salary;
        private double taxRate = 0.05;
        

        public string Name { get; set; }
        public double YearOfExp { get; set; }

        public double YearlyMedicalAllowance {get; private set;}

        public Employee()
        {
            this.YearlyMedicalAllowance = 30000;
        }

        public double Salary
        {
            get { return salary; }
            set {
                if (value > 200000)
                    salary = value - value * taxRate;
                else
                    salary = 5000;
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee objEmployee = new Employee();
            objEmployee.Name = "Rafiqul Islam";
            objEmployee.YearOfExp = 7;
            objEmployee.Salary = 5000;
            
            Console.WriteLine(objEmployee.Name);
            Console.WriteLine("Salary: " + objEmployee.Salary);
            Console.WriteLine("Yearly Madical Allowance" + objEmployee.YearlyMedicalAllowance);

            Console.ReadLine();
        }
    }

Static Constructor and C# implementation

Static Constructor

  • Instance constructors are used to initialize an object
  • Static constructors are used to initialize a class
  • Will only ever be executed once
  • Run before the first object of that type is created.
  • Have no parameter
  • Do not take an access modifier
  • May co-exist with a class constructor

Syntax:

        class Lion
        {
            static Lion()
            {
                // class-specific initialization
            }
        }

Example:


class RandomNumberGenerator
{
private static Random randomNumber;
public static string AuthorName { get; set; }

public RandomNumberGenerator(String msg)
{
Console.WriteLine(msg);
//Constructor for object
}

//Static constructor
static RandomNumberGenerator()
{
AuthorName = “Mahedee Hasan”;
randomNumber = new Random();
}

public int Next()
{
return randomNumber.Next();
}
}

class Program
{
static void Main(string[] args)
{
RandomNumberGenerator randomNumber
= new RandomNumberGenerator(“Generate 10 Random Number”);

for (int i = 0; i < 10; i++) { Console.WriteLine(randomNumber.Next()); } Console.WriteLine(“Author Name: ” + RandomNumberGenerator.AuthorName); Console.ReadKey(); } } [/csharp]

Love Calculator using C#

Love Calculator

    public class LoveCalculator
    {
        public string GetResults(string name1, string name2)
        {
            return GetCount(name1, name2);
        }
        private string GetCount(string firstName, string secondName)
        {
            try
            {
                string first = firstName.ToUpper();
                int firstlength = firstName.Length;
                string second = secondName.ToUpper();
                int secondlength = secondName.Length;
                int LoveCount = 0;

                for (int Count = 0; Count < firstlength; Count++)
                {
                    string singleLetter = first.Substring(Count, 1);
                    if (singleLetter.Equals("A")) LoveCount += 2;
                    if (singleLetter.Equals("E")) LoveCount += 2;
                    if (singleLetter.Equals("I")) LoveCount += 2;
                    if (singleLetter.Equals("O")) LoveCount += 2;
                    if (singleLetter.Equals("U")) LoveCount += 3;
                    if (singleLetter.Equals("A")) LoveCount += 1;
                    if (singleLetter.Equals("E")) LoveCount += 3;
                }
                for (int Count = 0; Count < secondlength; Count++)
                {
                    string singleLetter = second.Substring(Count, 1);
                    if (singleLetter.Equals("A")) LoveCount += 2;
                    if (singleLetter.Equals("E")) LoveCount += 2;
                    if (singleLetter.Equals("I")) LoveCount += 2;
                    if (singleLetter.Equals("O")) LoveCount += 2;
                    if (singleLetter.Equals("U")) LoveCount += 3;
                    if (singleLetter.Equals("A")) LoveCount += 1;
                    if (singleLetter.Equals("E")) LoveCount += 3;
                }
                int amount = 0;
                if (LoveCount > 0) amount = 5 - ((firstlength + secondlength) / 2);
                if (LoveCount > 2) amount = 10 - ((firstlength + secondlength) / 2);
                if (LoveCount > 4) amount = 20 - ((firstlength + secondlength) / 2);
                if (LoveCount > 6) amount = 30 - ((firstlength + secondlength) / 2);
                if (LoveCount > 8) amount = 40 - ((firstlength + secondlength) / 2);
                if (LoveCount > 10) amount = 50 - ((firstlength + secondlength) / 2);
                if (LoveCount > 12) amount = 60 - ((firstlength + secondlength) / 2);
                if (LoveCount > 14) amount = 70 - ((firstlength + secondlength) / 2);
                if (LoveCount > 16) amount = 80 - ((firstlength + secondlength) / 2);
                if (LoveCount > 18) amount = 90 - ((firstlength + secondlength) / 2);
                if (LoveCount > 20) amount = 100 - ((firstlength + secondlength) / 2);
                if (LoveCount > 22) amount = 110 - ((firstlength + secondlength) / 2);
                if (firstlength == 0 || secondlength == 0) amount = 0;
                if (amount < 0) amount = 0;
                if (amount > 99) amount = 99;
                return amount.ToString();
            }
            catch (Exception ex)
            {
                return "There is an error!!" + ex.ToString();
            }
        }
    }


    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Love Calculator");

            while (true)
            {
                Console.Write("Enter First Name:");

                string name1 = Console.ReadLine();
                Console.Write("Enter Second Name:");

                string name2 = Console.ReadLine();

                LoveCalculator loveCalculator = new LoveCalculator();
                string result = loveCalculator.GetResults(name1, name2);
                Console.WriteLine("Love Result :" + result + "%");
                Console.WriteLine("Press q to exit");
                string quit = Console.ReadLine();
                if (quit.ToLower().Trim() == "q")
                    break;
            }
        }
    }

How to remove special character from Unicode string

Here is the sample code to remove special character from Unicode string.
Sample Input: SG@%@sgs th? g#%@^@#$ chào^#^$#!abc35| _ sgs _35 hello world không gsg
Sample Output: SG%sgs th? g#%^#$ chào^#^$#!abc35 sgs 35 hello world không gsg

    class Program
    {
        static void Main(string[] args)
        {
            string inputString = "SG@%@sgs thể g#%@^@#$ chào^#^$#!abc35| _ sgs _35 hello world không gsg";

            string outputString = inputString.Replace("@", "").Replace("|", "").Replace("_", "");

            Console.WriteLine(inputString);
            Console.WriteLine(outputString);
            Console.ReadKey();
        }
    }

Factorial Calculator using C#

Factorial is a positive number is the product of all number less than or equal to the positive number.
For example:

0! = 1
1! = 1
2! = 2 * 1! = 2
3! = 3 * 2! = 6

n! = n * (n – 1)!

Here is the sample code to calculate Factorial using both loop and recursion using c#.


///

/// Author: Md. Mahedee Hasan
///

class Program
{
static void Main(string[] args)
{
int number = 0;
Console.WriteLine(“Enter an integer number to calculate factorial: “);
Int32.TryParse(Console.ReadLine(), out number);

Console.WriteLine(“Factorial of ” + number + ” is: ” + CalculateFactoial(number));
Console.WriteLine(“Factorial of ” + number + ” is: ” + Factorial(number));
Console.ReadLine();
}

//Calculate factorial using loop

private static int CalculateFactoial(int number)
{
int factorial = 1;
for (int counter = 1; counter <= number; counter++) { factorial = factorial * counter; } return factorial; } //Calculate factorial using recursion private static int Factorial(int number) { if (number == 0) return 1; else return number * Factorial(number – 1); } } [/csharp]

How to check Palindrome word using C#

Palindrome word can be read in both direction. Suppose “level” can be read in both direction, so it is palindrome word. To check palindrome word you can try like following code using C#.


    class Program
    {
        public static bool IsPalindrome(string word)
        {
            int minLength = 0;
            int maxLength = word.Length - 1;
            while (true)
            {
                if (minLength > maxLength)
                {
                    return true;
                }
                char a = word[minLength];
                char b = word[maxLength];
                if (char.ToLower(a) != char.ToLower(b))
                {
                    return false;
                }
                minLength++;
                maxLength--;
            }
        }

        static void Main()
        {
            string[] palindromeWord = {"aibohphobia","Dhaka","alula","cammac","Civic", "deified","deleveled",
                                 "detartrated","devoved","History","evitative","level","","mahedee"};

            foreach (string word in palindromeWord)
            {
                if (IsPalindrome(word))
                {
                    Console.WriteLine(word + " is a Palindrome");
                }
                else
                {
                    Console.WriteLine(word + " is not a Palindrome");
                }
            }
            Console.ReadKey();
        }
    }

How to find prime number between 1 to n


class Program
{
static void Main(string[] args)
{
//int n = 100000;
int n = 0;
Console.WriteLine(“Type an integer number to get prime number between 1 to n”);
Int32.TryParse(Console.ReadLine(), out n);
PrintPrimes(n);
}

public static void PrintPrimes(int n)
{
bool isPrime = false;
for (int i = 2; i < n; i++) { isPrime = true; for (int j = 2; j <= Math.Sqrt(i); j++) { if (i % j == 0) { isPrime = false; break; } } if (isPrime) Console.Write(i + ” “); } Console.ReadKey(); } } [/csharp] [wpdm_file id=51]

Draw star pyramid using C#

Sample input: 5
Sample output:

code-01

Code:


/*Author: Md. Mahedee Hasan*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StarPyramid
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Enter a number to draw pyramid: “);
int nRow = 0;
nRow = Convert.ToInt32(Console.ReadLine());

for (int row = 1; row <= nRow; row++) { for (int leftSpace = row; leftSpace <= nRow; leftSpace++) { Console.Write(” “); } for (int star = 1; star <= 2 * row – 1; star++) { Console.Write(“*” + ” “); //Print star and space } Console.WriteLine(); } Console.ReadKey(); } } } [/csharp] [wpdm_file id=50]