Saturday, April 6, 2013

Learn Microsoft C#.NET by Example



1. Hello World


using System;

public class HelloWorld {

    public static void   Main(string[] args)
    {
              
        System. Console.WriteLine("Hello World" );
        System. Console.ReadKey();

    }

}

  
2. Variables - Part I

using System;

public class Variables_I {

    public static void   Main(string[] args)
    {
              
        //A Variable is a piece of information; it has a data type and a value


          //1. Declare a variable
            //TYPE  NAME    SEMI-COLON
            int outcome;
            //COMPILE TIME ERROR: Use of unassigned local variable 'outcome'
            //System.Console.WriteLine("1. outcome=" + outcome);
 
            //2. Change the value of a variable
            //NAME  ASSIGNMENT OPERATOR VALUE   SEMI-COLON
            outcome = 42;
 
            System.Console.WriteLine("2. outcome=" + outcome);


        //another example:
        //data type: int
        //variable name: age
        //value:24
        int age=24;
        System. Console.WriteLine("My Age is " +age);


 
            string text = "hello world";
            //text = "Hello World";
            System.Console.WriteLine(text);

       
System. Console.ReadKey();

    }

}

  
3. Data Types - Part I

using System;

 public class DataTypes_I {

        public static void  Main( string[] args)
       {

           string strVar = "C# Data Types:";
 
            System.Console.WriteLine(strVar);
 
       
               byte by=129;//=>only +ive values
               short s=90;

            bool flag = true;//8 bits

            sbyte b = 2;

            int iNum = 123;//32 bits
            long lNum = 123;//64 bits
            float fNum = 123.2f;//32 bits
            double dNum = 123.2;//64 bits
            decimal DNum = 123.999m;//128 bits
            char ch = 'A';//16 bits
          //sbyte=including -ive
values
               //uint,ulong,ushort=>only +ive values
            double ans = iNum + lNum + fNum + dNum;//nb. +ch is also pssible             //convert any data type into its string value by calling ToString() method             System.Console.WriteLine(ans);             //decimal  ans1 = dNum + DNum  ;//Invalid: decimal cant be mixed with double and float             decimal ans1 = iNum + DNum;//Valid: decimal can be mixed with int and long             System.Console.WriteLine(ans1.ToString());
//************* IMPORTANT NOTE************//
//string concatenation: using + with string will combine the number with string as text
            string str = "My age is"+10+12;//will output "My age is 1012" not "My age is 22"!
            str = "My age is" + (10 + 12);//will output "My age is 22"!

//************* IMPORTANT NOTE************//

// All numeric data types as well as char data types have two use full methods , parse and TryParse, to convert string value into 
            //primitive numeric /char types:
            int num=int.Parse("23");
            char c = char.Parse("A");
            double d = double.Parse("1.3");
            double dbl = double.Parse("ccc");//this will produce a runtime error/exception
 
            //TryParse ensures that there is no runtime error while trying to parse
            int i;
            bool Ok = int.TryParse("345"out i);//on successful parse, TryParse will put 345 in i
            bool notOk=int.TryParse("A",out i);//on failure, TryParse will put default value(0) in i
       }

 }


4. Arithmetic Operators

using System;

public class ArithmeticOperators {

        public static void  Main( string[] args)
       {
               //+-%*/++--
 
int int_ans = 1 + 3;
 
            double dbl_ans_with_unexpectedly_wrong_result = 1 / 3;
            System.Console.WriteLine("Answer:" + dbl_ans_with_unexpectedly_wrong_result);//t
 
            double dbl_ans_with_expected_result = 1 / 3.0;//any one operand MUST BE of type double!!
            System.Console.WriteLine("Answer:" + dbl_ans_with_expected_result);//t
 
            double ans = 1 + 3 * 4 - 9 / 5;//any calc that involves / or * MUST have double as result data type!
 
            System.Console.WriteLine("Answer:" + ans);//this is called string concatenation
 
            // Override precedence: Use parentheses to force ur precedence
            ans = (1 + 3) * (4 - 9) / 5;//WILL FIRST CALCULATE THE NUMBERS INSIDE THE ROUND-BRACKETS
            System.Console.WriteLine("Answer:" + ans);
 
            //mod operator: % gives only the remainder
            ans = 5 % 2;
            System.Console.WriteLine("Remainder:" + ans);
            // Increment or decrement a numeric (int/long) variable
            int outcome = 0;
            int bb = 9;
            bb = bb + outcome++;//outcome is 42
            //or
            outcome = outcome + 1;
            //same way:
            outcome--;
            outcome = outcome - 1;
 
            System.Console.WriteLine("outcome=" + outcome);//outcome has become 43
            System.Console.WriteLine("outcome=" + outcome++);//WILL ADD 1 TO outcome LATER i.e. after this use
 
            ++outcome;//WILL ADD 1 TO outcome FIRST
            System.Console.WriteLine("outcome=" + outcome);
//************* IMPORTANT NOTE************//

//+ operator can be combined with =
            int i = 6;
            i += 5;//means: i=i+5;
            //similarly:
            string str = "My name is ";
            str += "Zeeshan";//This is equvalent to str=str+"Zeeshan" and this will output "My name is Zeeshan" 
                           Console.ReadKey();

       }
 }

  
5. Boolean Operators

using System;

public class BooleanOperators {

        public static void  Main( string[] args)
       {
               //==,!=,>,<,>=,<=,!
               //e.g
               //1<=2
               //1 and 2 are called operands
               int a=3;
               int b=2;

               bool isMarried=true ;

               bool result=a>b;
               bool rs=!false ;
              rs=!isMarried;

               Console.WriteLine(isMarried);
               Console.WriteLine(rs);
bool result = 2 > 3;
            System.Console.WriteLine("result(2>3):" + result);
            result = 2 == 3;
            System.Console.WriteLine("result(2==3):" + result);
            result = 2 >= 3;
            System.Console.WriteLine("result(2>=3):" + result);
            result = 2 < 3;
            System.Console.WriteLine("result(2<3 nbsp="" span=""> + result);
            result = 2 <= 3;
            System.Console.WriteLine("result(2<=3):" + result);
            result = 2 != 3;
            System.Console.WriteLine("result(2!=3):" + result);
            result = !(true);//NOT
            System.Console.WriteLine("result(!true):" + result);
            result = !result; 
            System.Console.WriteLine("!result:" + result);               Console.ReadKey();

       }
 }

  
6. Conditions - Part I

using System;

public class Conditions_I {

        public static void  Main( string[] args)
       {
                //if (...)... else


//We use an if-statement, when we want to run a C# line of code or statement only if a condition is true
            //Syntax: if(){
            //          statement1;
            //          statement2;
            //          ...no limits...;
            //         }



        
               int age=37;

               if(age==37)
                      Console.WriteLine("You must be the Great ZEE" );
                       else if (age > 35)
                       {
                      Console.WriteLine("Assalam o Aalaikum Wr. Wbr. Bare Miyan" );
                       }
                       else
                       {
                      Console.WriteLine("Assalam o Aalaikum Wr. Wbr. Or Sultan, kia haal hen?");
                       }


int a = 2;
            if (a == 2)//will return true
                System.Console.WriteLine("a is 2");//so, for a=2, this line will execute
            if (a < 2)//will return false
                System.Console.WriteLine("a is less than 2");//now, for a<2 execute="" line="" nbsp="" span="" this="" will="">
            //Note that inside round brackets a boolean result is required
            //We can combine more than one conditions with logical operators: || or &&
            //e.g.
            if (a < 2 || a > 0)//net result will be true, because 2nd condition is true
                System.Console.WriteLine("a is less than 2 or greater than 0");//this line will execute coz a>0
            if (a > 0 && a > 2)//not both conditions are true, so net result is false
                System.Console.WriteLine("a is greater than 0 AND also greater than 2");//this line will NOT execute coz a>2 returns false
            //we can use curly-brackets optionally for a single-line execution
            if (1 == 1)
                System.Console.WriteLine("Off course! 1 is equal to 1, you fool!");
            //or
            if (1 == 1)
            {
                System.Console.WriteLine("Off course! 1 is equal to 1, you fool!");
            }
            //but when you want multiple-line execution if your condition is true, then {} are must
            bool flag = true;
            if (flag == true)//or if(flag==true)
            {
                System.Console.WriteLine("Extra Info: the word flag is generally used in programming for bool type of variables");
                System.Console.WriteLine("Agr Yeh bat samajh nhi aai to msla nahi :-)");
            }
 
            //Use 'else' when you want to execute some code if your condition fails:
            //e.g.
            string name = "Ali";//Input some string here to execute else part of condition
            if (name == "")
                System.Console.WriteLine("Empty name.");
            else
                System.Console.WriteLine("I am " + name);
            //also conditions can be 'nested if-else' like:
            if (name == "Ali")
                System.Console.WriteLine("This is my friend, " + name);
            else if (name == "Akbar")
                System.Console.WriteLine("This is my cousin, " + name);
            else if (name == "Aslam")
                System.Console.WriteLine("This is my brother, " + name);
            //... no limts...
            else //finally, if no if-statement succeeds
                System.Console.WriteLine("Who is " + name + "?");
                    Console.ReadKey();
       
       }

}

  
7. Logical Operators

using System;

 public class LogicalOperators {

        public static void  Main( string[] args)
       {
        //Example Code:
        //1. These are two operators: && and ||
        //2. We use them to apply multiple conditions by combining multiple boolean expressions:
        //e.g

        //Logical OR: ||
        bool result = 2 > 3 || 2 == 3;
        System. Console.WriteLine("result(2 > 3 || 2==3):" + result);

        //Logical AND: &&
        result = 8 > 3 && 2 < 3;
        System. Console.WriteLine("result(2 > 3 && 2==3):" + result);
       
        int i=9;
        if(i>0 && i%2==0)
                System. Console.WriteLine("Even number" );
        if(i>0 && i%3 == 0 && i%5!=0 )
                System. Console.WriteLine("Numbers that are divisible by 3 but not by 5");

        if(age>15 && age<30 amp="" sex="=</span">"MALE")
                System. Console.WriteLine("Allowed" );
        else
            System. Console.WriteLine("Not Allowed: Only Male are allowed aged 15-30");

        bool isMarried=true ;
        bool age=12;

        if(age>20 && !isMarried)
                System. Console.WriteLine("Unmarried people whose age is more  than 20");


            bool result2 = 2 > 3 || 2 == 3;
            System.Console.WriteLine("result(2 > 3 || 2==3):" + result2);
            //Logical AND: &&
            result2 = 8 > 3 && 2 < 3; 
            System.Console.WriteLine("result(2 > 3 && 2==3):" + result2);       
       }
    
 }

    
8. Casting - Part I

using System;

 public class Casting_I {

        public static void  Main( string[] args)
       {

//Casting means to convert a type into another type; this is called casting:
            //1. all smaller types can be cast into bigger types; this is called 'implicit cast'
            //2. all bigger types can be cast into smaller types; this is called 'explicit cast':
            //Syntax:
            // =()
            //e.g.
            int a = 2;
            long b = a;//this is called casting implicitly
 
            //but            
 
            //int c = b;//compile-time error:Cannot implicitly convert type 'long' to 'int'. 
 
            //so the right way is:
            int d = (int)b;//this is called casting 'explicitly'
            System.Console.WriteLine("d:" + d);

//more examples:
               byte b=2;
               int i=b;
               short s=(short )i;
              System. Console.WriteLine("Result is" +i);
               char c='a' ;
               byte ii=(byte )c;
              System. Console.WriteLine("Result of ii" +ii);
               long l=1122;
               int i2=(int )l;
              System. Console.ReadKey();

       }
    
 }

  

9. Enums

using System;

 public class Enum_Part_I {


//Enums are special types which we make ourselves 'to name some constant values'; enums can't be declared inside a method
        //Declaring an enumeration type:
        //Write the keyword enum, followed by the name of the enum , 
        //followed by a pair of curly-brackets containing 
        //a comma-separated list of the enumeration member names
        public enum Season { Spring, Summer, Fall, Winter }
        //NB. By default enumeration members have integer values according to their index/position 
        // 0 for Spring, 1 for Summer, 2 for Fall & 3 for Winter 
        //BUT, we can also assign our custom int values, like:
        public enum GradeMinimum { C = 50, B = 60, A = 70, A1 = 80 }
 
 
 
        public enum Month
        {
            January, February, March, April,
            May, June, July, August,
            September, October, November, December
            //NB. enum members can be in single/multiple lines without any semi-colon
        }
        //we can specify what type of numeric value enum members will have:
        enum MinimumAge : uint //0,1,2,3,
        {
            Children = 1, Young = 16, Old = 30
        }
        //
        enum IELTS : byte
        {
            Poor = 3, Good = 5, Excellent = 8
        }
public enum ChildrenTypes
 {
  Smart, Fat, Skinny
 }
 public enum Grades
 {
  A=80, B=70, C=60, D=50
 }
 public enum AgeRangebyte
{
  teenager=20,young=30,old=50
}
        public static void  Main( string[] args)
       {

//all enums are strings
            Console.WriteLine(Month.January); // writes out 'January'  
            Console.WriteLine(Season.Fall); // writes out 'Fall'
            //but they can be cast into int; in this case we get the index/position as an int value
            Console.WriteLine((int)Season.Fall); // writes out '2'
            //interestingly we can use enums both as a string and as an int:
            Console.WriteLine(GradeMinimum.A + " Grade's Minimum Value is " + (int)GradeMinimum.A);

 ChildrenTypes ctypes = ChildrenTypes.Fat;
  int S = (int)ChildrenTypes.Skinny;

  System.Console.WriteLine(ChildrenTypes.Smart);
  System.Console.WriteLine(Skinny);
  System.Console.WriteLine((byte)AgeRange.teenager); 
  System.Console.WriteLine((byte)Grades.D);

  System.Console.ReadKey();
 }


 } 

10. Conditions - Part II

using System;

public class Conditions_II {

        public static void  Main( string[] args)
       {
// SWITCH ...
// We can use switch to avoid many if-else if-else if-... conditions
// switch statement can check anything: strings, numbers, enums,char, etc
// every switsh case MUST have a break;
// switch last case is called default: which is the same as 'else'
            //Just as we checked 'name' variable on different possible values: Ali, Akbar, Aslam             //Similarly, we can check variables' values by passing in a switch block like:             switch (name)             {//name could be char, bool or a numeric variable                 case "Ali":                     System.Console.WriteLine("This is my friend, " + name);                     break;//must                 case "Akbar":                     System.Console.WriteLine("This is my cousin, " + name);                     break;                 case "Aslam":                     System.Console.WriteLine("This is my brother, " + name);                     break;                 //... no limts...                     default//will work if all cases fail                     System.Console.WriteLine("Who is " + name + "?");                     break;             }             //NB. Enums can also be used with switch             Month m = Month.January;             switch (m)             {                 case Month.January:                     System.Console.WriteLine("It's very cold.");                     break;                 case Month.June:                     System.Console.WriteLine("It's very hot.");                     break;             }             //NB. Enums can be compared in 3 ways:             //an enum member versus an enum member:             if (m == Month.January)                 System.Console.WriteLine("It's very cold.");             else if (m == Month.June)                 System.Console.WriteLine("It's very hot.");             //or, an int versus an enum member int value             int userInputValue = 0;             if (userInputValue == (int)Month.January)                 System.Console.WriteLine("It's very cold.");             else if (userInputValue == (int)Month.June)                 System.Console.WriteLine("It's very hot.");             //or an string versus an enum member's string value              string userInput = "0";             if (userInput == Month.January.ToString())                 System.Console.WriteLine("It's very cold.");             else if (userInput == Month.June.ToString())                 System.Console.WriteLine("It's very hot.");
//************* IMPORTANT NOTE************//
//we can combine cases by omitting their break; statement
            //this is equvalent to using ||
            int value = 2;
            switch (value)
            {
 
                case 2:
                case 3:
                case 5:
                case 6:
                    Console.WriteLine("Value accepted:"+value);
                    break;
                default:
                    Console.WriteLine("Value NOT accepted:" + value);
                    break;
            }
            //OR
            if(value==2||value==3||value==4||value==5||value==6)
                Console.WriteLine("Value accepted:" + value);
            else
                Console.WriteLine("Value NOT accepted:" + value);
          }
    }
     

11. String class methods

using System;

public class StringClass {

        public static void  Main( string[] args)
       {

// .net string class provides many useful methods to play with a string variable:
// for example:

 
   string str = "ZeE";
 
            Console.WriteLine("In the following, the sample string (str) is {0}", str);
 
            bool equals = str.Equals("zee");
            Console.WriteLine("str.Equals({0}) gives result: {1}""zee", equals);
 
            int len = str.Length;
            Console.WriteLine("str.Length gives result: {0}", len);
 
            int compareTo = str.CompareTo("zee");//-1,0,1
            Console.WriteLine("str.CompareTo({0}) gives result: {1}""zee", compareTo);
 
            bool contains = str.Contains("z");
            Console.WriteLine("str.Contains({0}) gives result: {1}""z", contains);
 
            bool endsWith = str.EndsWith("E");
            Console.WriteLine("str.EndsWith({0}) gives result: {1}""E", endsWith);
 
            int indexOfE = str.IndexOf("E");
            Console.WriteLine("str.IndexOf({0}) gives result: {1}""E", indexOfE);
 
            int lastIndexOfE = str.LastIndexOf("E");
            Console.WriteLine("str.LastIndexOf({0}) gives result: {1}""E", lastIndexOfE);
 
            string replace = str.Replace("Z""z");
            Console.WriteLine("str.Replace({0},{1}) gives result: {2}""Z""z", replace);
 
            bool startsWithE = str.StartsWith("E");
            Console.WriteLine("str.StartsWith({0}) gives result: {1}""E", startsWithE);
 
            string EE = str.Substring(1);
            Console.WriteLine("str.Substring({0}) gives result: {1}", 1, EE);
 
            string e = str.Substring(1, 1);
            Console.WriteLine("str.Substring({0},{1}) gives result: {2}", 1, 1, e);
 
            string zee = str.ToLower();
            Console.WriteLine("str.ToLower() gives result: {0}", zee);
 
            string ZEE = str.ToUpper();
            Console.WriteLine("str.ToUpper() gives result: {0}", ZEE);
 
            char[] strLetters = str.ToCharArray();//'Z', 'e', 'E'
 
            str = "Zee ";
            Console.WriteLine("In the following, the sample string (str) is {0}", str);
            Console.WriteLine("str Length is : {0}", str.Length);
            string Zee = str.Trim();
            Console.WriteLine("str.Trim() Length is : {0}", Zee.Length);
 
            str = "A, B, C";
            string[] comma_separated = str.Split(',');//"Cloneable"," ShadowingMember"," C"
            string[] space_separated = str.Split(' ');//"Cloneable,", "ShadowingMember,", "C"
            /**Output:
            In the following, the sample string (str) is ZeE
            str.Equals(zee) gives result: False
            str.Length gives result: 3
            str.CompareTo(zee) gives result: 1
            str.Contains(z) gives result: False
            str.EndsWith(E) gives result: True
            str.IndexOf(E) gives result: 2
            str.LastIndexOf(E) gives result: 2
            str.Replace(Z,z) gives result: zeE
            str.StartsWith(E) gives result: False
            str.Substring(1) gives result: eE
            str.Substring(1,1) gives result: e
            str.ToLower() gives result: zee
            str.ToUpper() gives result: ZEE
            In the following, the sample string (str) is Zee
            str Length is : 4
            str.Trim() Length is : 3
            **/
        }
}
12. Arrays  - Part I
public class Arrays_PartI
    {
        public static void Main(string[] args)
        {
            //creating an empty array
            byte[] marks = new byte[2];
 
            Console.WriteLine(marks[0]);//default value:0
            byte last = marks[1];//accessing an array item
 
            marks[7] = 15;//filling an array elemnt            
            Console.WriteLine(marks[7]);
 
            Console.WriteLine(last);
 
            string[] s = new string[8];//an array of eight empty strings
            s[3] = "Sultan";
            Console.WriteLine(s[3]);
 
            double[] d = new double[8];//an array of eight double numbers
 
            Console.WriteLine(d[3]);//default value: 0
 
            bool[] b = new bool[8];
 
            Console.WriteLine(b[3]);//default value: false
            Console.ReadKey();
        }
 
 
    }
13. Loops  - Part I
public class Loops_PartI
    {
        public static void Main(string[] args)
        {
   //Iteration means loops, i.e. to repeat some code for a specific no. of time
            //C# has the following four looping constructs:
            // for, foreach, while, do...while
            //FOR LOOP:
            /*
            Syntax:
            for (; ; )
            {
            ...
             statements
            ...
            }
            */
            //e.g.
            for ( int i = 0; i < 3; i++)
                System. Console.WriteLine( "i:" + i); //single-line code: no need to enclose in {}
            //we can split for-loop parts like this:
            int ii = 0;
            for (; ii < 3; )
            {
                System. Console.WriteLine( "ii:" + ii);
                ii++;
            }
            //NB. this also shows the sequence of processing:
            //1. initialize control variable (here, int ii = 0;),
            //2. execute code in {},
            //3. update control variable (here, i++),
            //4. check the status of condition (here, ii < 3)
            //NB. for multiple-lines of code {} are must
//Nested Loop : Aloop inside another loop
//e.g. This example program uses nested loop to search for vowels in a string
string aString="Zeeshan" ;
               char [] vowels= { 'a', 'e', 'o', 'u', 'i'};
        string vowelsFound= string.Empty;
           
               for ( int i =0; i
              {
                     
                      Console.WriteLine( "Checking : " +aString[i]);
                      for ( int j=0; j
                     {
                            Console.WriteLine( "With: " +vowels[j]);
                            if(aString[i]==vowels[j])
                           {
                    if(!vowelsFound.Contains(vowels[j].ToString()))
                                  vowelsFound+= ", " +vowels[j];
break ;
                           }
                     }
              }
Console .WriteLine("Vowels in {0} are {1}." ,aString,vowelsFound.Remove(0,1));

14. Math class
public class MathClass
    {
        public static void Main(string[] args)
        {
//Math class provides static methods to deal with numeric data
            int unsignedInt = Math.Abs(-2);
            Console.WriteLine( "Math.Abs({0})={1}" , -2, unsignedInt);
            double least = Math.Floor(2.4);
            Console.WriteLine( "Math.Floor({0})={1}" , 2.4, least);
            double largest = Math.Ceiling(2.4);
            Console.WriteLine( "Math.Ceiling({0})={1}" , 2.4, largest);
            int max = Math.Max(1, 2);
            Console.WriteLine( "Math.Max({0},{1})={2}" , 1, 2, max);
            int min = Math.Min(1, 2);
            Console.WriteLine( "Math.Min({0},{1})={2}" , 1, 2, min);
            double pow = Math.Pow(2, 3);
            Console.WriteLine( "Math.Pow({0},{1})={2}" , 2, 3, pow);
            double rounded = Math.Round(2.4);
            Console.WriteLine( "Math.Round({0})={1}" , 2.4, rounded);
            double sqrt = Math.Sqrt(4);
            Console.WriteLine( "Math.Sqrt({0})={1}" , 4, sqrt);
          
          /** Output:
            Math.Abs(-2)=2
            Math.Floor(2.4)=2
            Math.Ceiling(2.4)=3
            Math.Max(1,2)=2
            Math.Min(1,2)=1
            Math.Pow(2,3)=8
            Math.Round(2.4)=2
            Math.Sqrt(4)=2
             */
         }
     }
15. Object Oriented Programming (OOP) - Classes: Part I
/* Theory:
         * Object: object is our-own-defined data type which can store more than one data of some concept
         * e.g Employee, ContactInfo, Animal, Department, Cursor, System, Student, etc
         * class: a class is the coded-description of such a concept/object in a programming language
         *
         * A class may or may not be inside a namespace
         * A namespace is just a block {} with any number of classes
         * A namespace block is used to group similar type of classes
         * A name space name can contain single word or multiple words separated by .:
         * e.g. namespace MyApp{} , namespace MyApp.Classes or namespace com.zeesoft.business {}
         *
         * The description of an object (i.e. class) consists of different segments of code called class members:
         * variables, constructors,destructor,properties,methods
         *
         * Access Modifiers: C# keywords telling a programmer in which context a member can be accessed:
         * public: accessible from anywhere; within and from any other class,
         * protected: only accessible in a child class
         * internal: only accessible within a namespace,
         * private: only accessible within a class,
         * Constructors: the code-block which helps create/initialize an object;
         * it can be more than one;
         * at least one constructor is already present for all the objects
         * whether we explicitly make it or not called no-arguments constructor
         *
         * Methods: the code-blocks which process data in some way;
         * they form behavior of an object;
         * a method signature means: ()
         * Properties: the code-blocks used to change/get variables of an object
         * Destructor: the code-block which gets called by .net Garbage Collector to release memory
         * static: variables/methods which hold data relating to all the objects of a class
         * non-static/instance: variables/methods which hold data only for a single instance/object of a class
         */
namespace OOP.Class1
{
using System;//using clauses are used to import other namespace's classes to use inside your class
    public class Person
    {
        // private variables
        int age;
        string name;
string nick;
        // default constructor
        public Person()
        {
            Console.WriteLine( "object created by new Person()" );
            //set default values
            Name = "Name not Set" ;
        }
        // constructor with parameters/arguments
        public Person( string _name)
        {
            Console.WriteLine( "object created by new Person(name)" );
            Name = _name;
        }
        public Person( int age)
        {
            Console.WriteLine( "object created by new Person(age)" );
            Name = "Mr Unknown";
            NickName = "" ;
            this.age = age;
        }
        public Person( string _name, int age)
        {
            Console.WriteLine( "object created by new Person(name,age)" );
            name = _name;
            this.age = age;
        }
        //properties: characteristics/information/data/features of a class
        public int Age
        {
            get
            {
                return age;
            }
            set {
                    if (isValidAge(value))
                    age= value;
}
        }
  public bool isValidAge( int ageNum)
        {
            if (ageNum == 0 || ageNum < 0)
                return false;
            else
                return true;
        }
        public string Name
        {
            get
            {
                return name;
            }
            set { name = value; }
        }
 
 //read only property: which only has getter and no setter
        public string AgeLevel
        {
            get
            {

                      if (age > 0 && age <= 30)
                    return "Young " ;
                else if (age >30 )
                    return "Old " ;
                else //if (age <= 0)
                    return "" ;//unknown 
            }
        }
 //write-only property: which only has setter and no getter
        public string NickName
        {            
            set { nick= value; }
        }
        //methods: operations/actions/behavior of a class
        public void displayPersonInfo()
        {
           
if (!string .IsNullOrEmpty( this.nick))
                Console.WriteLine( "{0}{1} ({2}) is of age {3}" , AgeLevel, Name, this .nick, Age);
            else
                Console.WriteLine( "{0}{1} is of age {2}" , AgeLevel, Name,Age);
        }
       
    }
    public class Tests
    {
        public static void Main( string[] args)
        {
            Person p0 = new Person(10);
            p0.displayPersonInfo();
            Person p = new Person( "Zeeshan" , 12);
p.NickName="ZEE";
            p.Age = 38;
  p.displayPersonInfo();
            Person p2 = new Person( "Ali" );
            p2.Age = 23;          
            p2.displayPersonInfo();
            Console.ReadKey();
        }
    }
}