Saturday, March 26, 2016

C# - Static Elements

Static Variable

When using an object oriented platform, we can create a variable in a class (int, double, char…) that will replicated per instance of the class. The static variables are used to reduce this replication and allowing us to create a single variable that is used at the class level.


In addition :

·       Static variable is created only one time for all instances.
·       When working with different classes we can use the Static variable without creating an instance of the class.
·        Static variables are configured only one time in memory.
·        Calling to a static variable made with "ClassName.Varable".

Example:
In the following code I'll demonstrate a static variable that updated per call no matter the class instance that use it.
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            BankAccounts ClientA = new BankAccounts("Alfred");
            Console.WriteLine(BankAccounts.TotalMonyInBank);
            BankAccounts ClientB = new BankAccounts("Hulk");
            Console.WriteLine(BankAccounts.TotalMonyInBank);
            BankAccounts ClientC = new BankAccounts("Philip");
            Console.WriteLine(BankAccounts.TotalMonyInBank);
            BankAccounts ClientD = new BankAccounts("Alex");
            Console.WriteLine(BankAccounts.TotalMonyInBank);
        }
    }

    class BankAccounts
    {
       public static int TotalMonyInBank = 0;
       
       public string AccountName { get; set; }

       public BankAccounts(string UserAccountName )
       {
           AccountName = UserAccountName;
           TotalMonyInBank = TotalMonyInBank + 100;
       }
    }
}

Result : 









Static Functions:

Static functions are executed on the class level and not for a specific object, therefore like every other component that configured with 'Static' we have few conditions that must be applied before we can access it.

Conditions and Specifications:
·         Not like a NON static function, we can access static function only via Class level.
·         Every function should be declared with the 'static' keyword.
Example:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(StaticExample.Calculation(10,2));     
        }
    }

    class StaticExample
    {
        public static int Calculation(int num1, int num2)
        {       
            return   (num1 * num2)*3;
        }
    }

Result : 








Static Properties

Static property are configured in the same way we configured a variable, all we need to do is to configure the property with  the 'Static' word after the security key.

Non Static Property:

class StaticExample
    {
        //Full Property
        private int example1;
        public int Example1
        {
            get { return example1; }
            set { example1 = value; }
        }

        //Short Property
        public int Example2 { get; set; }
    }

Static Property:

class StaticExample
    {
        //Full Property
        private static int example3;
        public static int Example3
        {
            get { return example3; }
            set { example3 = value; }
        }

        //Short Property
        public static int Example2 { get; set; }
    }


Note!
Like a static variable, we access static Proporty with ClassName.Proporty

class Program
    {
        static void Main(string[] args)
        {
            StaticExample instance1 = new StaticExample();
            //instance1 --we cannot use it to update the static Prop
            StaticExample.Example1 = 50;
            StaticExample.Example2 = 100;
        }
    }

C# - Break And Continue

The "Break and continue"  are saved words in C# (you cannot use them as a name for variable/function...), these two terms are used to manipulate the Loop execution.

Continue

When using this "Continue" term, we actually tell the compiler that the current iteration is completed and therefore he need to finish with the current iteration and move to the next one.

Not like break, when using continue the loop will finish all iterations (if loop should run 20 times, the continue case will not cause any changes).
Example 1:

This example covers a simple loop without using any saved word, as a result, nothing will affect the loop execution
class Program
    {
        static void Main(string[] args)
        {
           int closeloop= 0;
            while (closeloop <= 5)
            {
                closeloop++;
            
                Console.WriteLine("Current iteration:{0} " , closeloop);   

                Console.WriteLine();

                Console.WriteLine("This code is reachable");
            }
        }
    }

 Result:
Example 2:
This example includes the ‘continue’ term, now you will  see that the code that appear afterwards will excluded on every  other iteration
class Program
    {
        static void Main(string[] args)
        {
           int closeloop= 0;
            while (closeloop <= 10)
            {
                closeloop++;      
                Console.WriteLine("Current iteration:{0} " , closeloop);
                continue;
                Console.WriteLine("This code is unreachable");
            }
        }
    }
Result:


Break
When using the ‘Break’ term, we are actually telling the compiler to END the entire loop execution (No matters how much more iterations are remained) and move to next code that appear after the loop.
Example 3:
This example demonstrates how the ‘Break’ ends the entire loop after the first iteration, and the execution will now move into the next code that appear after the loop.
class Program
    {
        static void Main(string[] args)
        {
           int closeloop= 0;
            while (closeloop <= 5)
            {
               closeloop++;
               Console.WriteLine("Current iteration:{0} " , closeloop);
               break;
               Console.WriteLine("This code is unreachable");
            }
            Console.WriteLine();
            Console.WriteLine("Code after breal");
        }
    }
Result:

C# - Working with Functions


Functions are a mandatory part of every basic application, this article will cover the main practical and theoretical aspects that you need when creating and using code functions


The Function structure

[Security type], Returned value, Function Name (Parameters)

Security Type – The security level of the method (Public, Private…)

Return Type – The return value of the function (variable, Array and no value(Void)).

Function Name – The function name that we need to use when calling it.

Parameters – The parameters that will be used in this function.

Note!
The function local parameters are relevant only to this function , therefore you can use the same variable names in other parts of your code.

How can we declare a new function...? 

Definition No'1:
The first option is to define a static method (we can call it via the class level, there is no need to create an object from the class).


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //Calling a static 'Void' function:
            math.def1();

            //Calling a static function that will return a value
            int methoedresult = math.def2(3,4);
            Console.WriteLine(methoedresult);
        }
    }

    class math
    {
        public static void def1()
        {
            Console.WriteLine("Math Class");       
        }

        public static int def2(int num1 , int num2)
        {
            int result;
            return result= num1 * num2;
        }
    }

}

Definition No'2:
The second option is to define a ‘Non-Static’ method (in this scenario you will need to create a class instance to get access).

class Program
    {
        static void Main(string[] args)
        {
            //Creating a class instance : 

            math ClassInstance = new math();

            //Calling the functions using a class instance:
            ClassInstance.def1();

            //Calling a methoed that return value:
            int methoedresult = ClassInstance.def2(3, 4);
            Console.WriteLine(methoedresult);
        } 
    }

    class math
    {
        public  void def1()
        {
            Console.WriteLine("Math Class");        
        }

        public int def2(int num1 , int num2)
        {
            int result;
            return result= num1 * num2;
        }
    }
}



Working with the Function Parameters 

Option No'1: The ‘Value’ parameter
By default, parameters are sent to a method as “Value”, that’s means that any manipulation on this parameter in the function will not affect the original variable value (When using the default value we actually send a copy of the variable).

Code Example:
In the following code, you will see that I sent to my function a single parameter that already initialized outside the function , in the function I changed the variable value but as you can see this change does not affect the original value.

class Program
    {
        static void Main(string[] args)
        {
            int v1 = 10;
            Example1(v1);
            Console.WriteLine("Value after function manipulation: " + v1);    
        }

        private static void Example1(int a)
        {
            a = 90;
            Console.WriteLine("Value in function : " + a);
        }
    }


Result: 







Option No'2: The ‘Reference’ parameter
This option will allow us to initialize a variable prior to sending it to the function, the difference from the ‘Value’ type is that every change that made inside the function will affect the original variable.

Note!
The reference parameter is moved to the function as it is (the original value) and not a copy

Code Example:
In this code you can see that the manipulation made in the function body affects the original value located outside the function.

class Program
    {
        static void Main(string[] args)
        {
            int v1 = 10;
            Example1(ref v1);
            Console.WriteLine("The Value after function manipulation: " + v1);
        }

        private static void Example1(ref int a)
        {
            a = 90;
            Console.WriteLine("Value in function : " + a);
        }

Result: 







Option No'3: Send parameters by ‘Outer’:
This option allows us to send a variable to a function without the need to initialize it (The initialization performed inside the function body).

Code Example :

Class Program
    {
        static void Main(string[] args)
        {
            int v1 ;
            Example1(out v1);
            Console.WriteLine("Value after function manipulation: " + v1);
        }

        private static void Example1(out int a)
        {
            a = 90;
            Console.WriteLine("Value in function : " + a);
        }
    }

Result:

Same result as shown in the ‘Ref’ part.

My Presentations