Menu Close

Category: Blog

ENUMS IN C#

WHY ENUMS

Enums are strongly typed constants

If a program uses set of integral numbers, consider replacing them with enums. otherwise the program becomes less
 > Readable
 > Maintainable

———————————————————————————————————————–

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            Customer[] customers = new Customer[3];

            customers[0] = new Customer
            {
                Name = “Malla”,
                Gender = 1
            };
            customers[1] = new Customer
            {
                Name = “mary”,
                Gender = 2

            };
            customers[2] = new Customer
            {
                Name = “hyyjjj”,
                Gender = 0
            };

            foreach (Customer customer in customers)
            {
                Console.WriteLine(“Name = {0} && Gender = {1}”, customer.Name, GetGender(customer.Gender));
                Console.ReadLine();
            }

        }

        public static string GetGender(int gender)
        {
            switch(gender)
            {
//      INTEGRAL NUMBERS BESIDE CASES SHOULD BE REPLACES WITH ENUMS TO //BETTER READABLE
                case 0:
                    return “Unknown”;
                case 1:
                    return “Male”;
                case 2: 
                    return “Female”;
                default:
                    return “Invalid data detected”;
            }
    }
        //0 Unknown
        //1  Male
        //2 Female

        public class Customer
        {
            public string Name { get; set; }
            public int Gender { get; set; }
        }
    }
}
————————————————————————————————————————

USE ENUMS FOR THE ABOVE PROGRAM MORE READABLE


using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            Customer[] customers = new Customer[3];

            customers[0] = new Customer
            {
                Name = “Malla”,
                Gender = Gender.Male
            };
            customers[1] = new Customer
            {
                Name = “mary”,
                Gender = Gender.Female

            };
            customers[2] = new Customer
            {
                Name = “hyyjjj”,
                Gender = Gender.Unknown
            };

            foreach (Customer customer in customers)
            {
                Console.WriteLine(“Name = {0} && Gender = {1}”, customer.Name, GetGender(customer.Gender));
                Console.ReadLine();
            }

        }

        public static string GetGender(Gender gender)
        {
            switch(gender)
            {
                case Gender.Unknown:
                    return “Unknown”;
                case Gender.Male:
                    return “Male”;
                case Gender.Female: 
                    return “Female”;
                default:
                    return “Invalid data detected”;
            }
    }
        //0 Unknown
        //1  Male
        //2 Female
        public enum Gender
        {
            Unknown,
            Male,
            Female
        };

        public class Customer
        {
            public string Name { get; set; }
            public Gender Gender { get; set; }
        }
    }
}


 ————————————————————————————————————————-
ENUMS USAGE


If a program uses set of integral numbers, consider replacing them with enums. otherwise the program becomes less
 > Readable
 > Maintainable

1.Enums are enumerations
2.Enums are strongly typed constants, Hence, an explicit cast is needed to convert from enum type to an integral type and vice versa.Also an enum of one type cannot be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
3. The default underlying type of an enum is int.
4.The default value for firt element is zero and gets incremently by 1.
5 it is possible to customize the underlying type and values.
6. Enums are value types.

7. Enum keyword (all small letters) is used to create enumerations. where as Enum class, contains staticGetValues() and GetNames() methods which can be used to list Enum underlying type values and Names.

Enum(with capital Eis a class)

enum (with small e is to create enumerations)

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            short[] Values = (short[])Enum.GetValues(typeof(Gender));

            foreach (int value in Values)
            {
                Console.WriteLine(value);     
            }
            string[] Names = Enum.GetNames(typeof(Gender));

            foreach (string name in Names)
            {
                Console.WriteLine(name);
                Console.ReadLine();
            }
       
    }
        //0 Unknown
        //1  Male
        //2 Female
       
        public enum Gender : short
        {
            Unknown = 1,
            Male = 5,
            Female = 23
        };

        public class Customer
        {
            public string Name { get; set; }
            public Gender Gender { get; set; }
        }
    }
}

Share this:

EXCEPTION ABUSE AND HOW TO RESOLVE IN C#

Exception Handling abuse


Exceptions are unforseen errors that occur when a program is running. For example, when an application is executing a query, the database connection is lost, Exception is generally used to handle scenarios.


Using exception handling to implement program logical flow is bad and is termed as exception handling abuse.

————————————————————————————————————————
using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            try
            {
                Console.WriteLine(“Please enter Numarator”);
                int Numarator = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine(“Please enter Denaminator”);
                int Denaminator = Convert.ToInt32(Console.ReadLine());

                int Result = Numarator / Denaminator;

                Console.WriteLine(“Result = {0}”, Result);
                Console.ReadLine();
            }
            catch(FormatException)
            {
                Console.WriteLine(“Please enter valid number “);
                Console.ReadLine();
            }
            catch(OverflowException)
            {
                Console.WriteLine(“Only numbers beteen {0} && {1}”, Int32.MinValue, Int32.MaxValue);
                Console.ReadLine();
            }
            catch(DivideByZeroException)
            {
                Console.WriteLine(“Denominator cannot be Zero”);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
    }
}
=======================================================================

EXCEPTION HANDLING ABUSE RESOLVED..

CORRECT WAY TO USE EXCEPTION HANDLING AFTER VALIDATION


using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            try
            {
                Console.WriteLine(“Please enter Numarator”);
                int Numarator;
                bool IsNumaratorConversionSuccessful = Int32.TryParse((Console.ReadLine()), out Numarator);

                if (IsNumaratorConversionSuccessful)
                {
                    Console.WriteLine(“Please enter Denominator”);
                    int Denominator;
                    bool IsDenominatorConversionSuccessful = Int32.TryParse((Console.ReadLine()), out Denominator);

                    if (IsDenominatorConversionSuccessful && Denominator != 0)
                    {
                        int Result = Numarator / Denominator;

                        Console.WriteLine(“Result = {0}”, Result);
                        Console.ReadLine();
                    }
                    else
                    {
                        if (Denominator == 0)
                        {
                            Console.WriteLine(“Denominator cannot be Zero”);
                            Console.ReadLine();
                        }
                        else
                        {
                            Console.WriteLine(“Denominator should be valid number between {0} && {1}”, Int32.MinValue, Int32.MaxValue);
                            Console.ReadLine();
                        }
                    }

                }
                else
                {
                    Console.WriteLine(“Numarator should be valid number between {0} && {1}”, Int32.MinValue, Int32.MaxValue);
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}


Share this:

INNER EXCEPTIONS IN C#

INNER EXCEPTION

The InnerException property returns the Exception instance that caused the current exception.

To retain the original exception pass it as a parameter to the constructor, of the current exception.

Always check if inner exception is not null before accessing any property of the inner exception object, else, you may get Null Reference Exception.

To get the type of InnerException use GetType() method.
————————————————————————————————————————–

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            try
            {
                try
                {
                    Console.WriteLine(“Please enter first number “);
                    int FN = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine(“Please enter second number “);
                    int SN = Convert.ToInt32(Console.ReadLine());

                    int Result = FN / SN;
                    Console.WriteLine(“Result = {0}”, Result);
                    Console.ReadLine();
                }

                catch (Exception ex)
                {
                    String filePath = @”C:somelog1.txt”;
                    if (File.Exists(filePath))
                    {
                        StreamWriter sw = new StreamWriter(filePath);
                        sw.Write(ex.GetType().Name);
                        sw.Close();
                        Console.WriteLine(“Please try later, there is a problem”);
                        Console.ReadLine();
                    }
                    else
                    {
                        throw new FileNotFoundException(filePath + “is not present”, ex);
                    }
                }

            }
            catch(Exception exception)
            {
                Console.WriteLine(“Current Exception ={0} “, exception.GetType().Name);
                if (exception.InnerException != null)
                {
                    Console.WriteLine(“Inner Exception = {0} “, exception.InnerException.GetType().Name);
                    Console.ReadLine();
                }
            }
        }
    }

}

Share this:

EXCEPTION HANDLING IN C#

EXCEPTION HANDLING IN C#

using System;
using System.IO;

namespace ConsoleApplication4
{

    class Program
    {


        public static void Main()
        {
            try
            {
                StreamReader streamreader = new StreamReader(@”C:UsersmallareddyOneDriveDocuments1Data.txt”);
                Console.WriteLine(streamreader.ReadToEnd());
                streamreader.Close();
                Console.ReadLine();
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
                // More specific exception at first, if you place general exception  first then it throughs exception as 
                // a previous catch clause already catches all exceptions of this or of a super type(‘System.Exception’)
            catch (FileNotFoundException ex)
            {
                //Console.WriteLine(ex.Message);
                //Console.WriteLine();
                //Console.WriteLine();
                //Console.WriteLine(ex.StackTrace);
                Console.WriteLine(“Please check if the file exist = {0}”, ex.FileName);
                Console.ReadLine();
            }
                // General exception at the bottom 
           
        }       
       
    }
}
===================================================================

CLASS HIERARCHY EXCEPTIONS
TRY , CATCH, CATCH..

using System;
using System.IO;

namespace ConsoleApplication4
{

    class Program
    {


        public static void Main()
        {
            try
            {
                StreamReader streamreader = new StreamReader(@”C:UsersmallareddyOneDriveDocuments1Data.txt”);
                Console.WriteLine(streamreader.ReadToEnd());
                streamreader.Close();
                Console.ReadLine();
            }

           
            catch (FileNotFoundException ex)
            {
                //Console.WriteLine(ex.Message);
                //Console.WriteLine();
                //Console.WriteLine();
                //Console.WriteLine(ex.StackTrace);
                Console.WriteLine(“Please check if the file exist = {0}”, ex.FileName);
                Console.ReadLine();
            }
                // General exception at the bottom 
            catch (Exception ex)
            {
                ConsolCe.WriteLine(ex.Message);
                Console.ReadLine();
            }
            // More specific exception at first, if you place general exception  first then it throughs exception as 
            // a previous catch clause already catches all exceptions of this or of a super type(‘System.Exception’)
        }       
       
    }
}
=======================================================================

COMPLETE EXCEPTION HANDLING



using System;
using System.IO;
namespace ConsoleApplication4
{
    class Program
    {
       
        public static void Main()
        {
            StreamReader streamreader = null;
            try
            {
                streamreader = new StreamReader(@”C:UsersmallareddyOneDriveDocumentsData.txt”);
                Console.WriteLine(streamreader.ReadToEnd());
                Console.ReadLine();
            }
            catch (FileNotFoundException ex)
            {
                //Console.WriteLine(ex.Message);
                //Console.WriteLine();
                //Console.WriteLine();
                //Console.WriteLine(ex.StackTrace);
                Console.WriteLine(“Please check if the file exist = {0}”, ex.FileName);
                Console.ReadLine();
            }
            // General exception at the bottom 
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
            // More specific exception at first, if you place general exception  first then it throughs exception as 
            // a previous catch clause already catches all exceptions of this or of a super type(‘System.Exception’)
            finally
            {
                if (streamreader != null)
                {
                    streamreader.Close();
                    Console.WriteLine(“Finally Block”);
                    Console.ReadLine();
                }
            }
        }
    }
}
}




















Share this:

DELEGATES IN C#

What is a delegate?


A delegate is a type safe function pointer. That is, it holds a reference (pointer) to a function.

The signature of the delegate must match the signature of the function,the delegate points to, otherwise you get a complier error. This is the reason delegates are called as type safe function pointers.

A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass in the funstion name as a parameter to the delegate constructor, and it is to this function the delegate will point to.

Tip to remember delegate syntax: Delegates syntax look very much similar to a method with a delegate keyword. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    class Program
    {
        public delegate void HelloFunctionDelegate(string Message);

    
        public static void Main()
        {

            HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
            del(“This is the delegate function”);
           // A delegate is a type safe function pointer
        }

        public static void Hello(string strMessage)
        {
            Console.WriteLine(strMessage);
            Console.ReadLine();
        }
    }
}
=======================================================================
DEMO DEMO ON DELEGATE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    class Program
    { 
        public static void Main()
        {

            List<Employee> empList = new List<Employee>();
            empList.Add(new Employee() { ID = 101, Name = “Malla”, Salary = 5000, Experience = 5 });
            empList.Add(new Employee() { ID = 102, Name = “Reddy”, Salary = 4000, Experience = 4 });
            empList.Add(new Employee() { ID = 103, Name = “Mathew”, Salary = 3000, Experience = 3 });
            empList.Add(new Employee() { ID = 104, Name = “Sam”, Salary = 6000, Experience = 7 });

            Employee.PromoteEmployee(empList);
            Console.ReadLine();
        } 
    }

    class Employee
    {
        public int ID{get;set;}
        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public static void PromoteEmployee(List<Employee> employeeList)
        {
            foreach (Employee employee in employeeList)
            {
                if (employee.Experience >= 5)
                {
                    Console.WriteLine(employee.Name + ” Promoted”);
                    Console.ReadLine();
                }
            }
        }
    }
}

=======================================================================
USING DELEGATE THE ABOVE EXAMPLE IS MODIFIED 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    class Program
    { 
        public static void Main()
        {

            List<Employee> empList = new List<Employee>();
            empList.Add(new Employee() { ID = 101, Name = “Malla”, Salary = 5000, Experience = 5 });
            empList.Add(new Employee() { ID = 102, Name = “Reddy”, Salary = 4000, Experience = 4 });
            empList.Add(new Employee() { ID = 103, Name = “Mathew”, Salary = 3000, Experience = 3 });
            empList.Add(new Employee() { ID = 104, Name = “Sam”, Salary = 6000, Experience = 7 });


            //IsPromotable ispromotable = new IsPromotable(Promote);

            //Employee.PromoteEmployee(empList, ispromotable);
                                             // Lamda expressions
            Employee.PromoteEmployee(empList,emp =>emp.Experience >=5);
            Console.ReadLine();
        } 
           //******** below commented section is to write shortcut code using lamda expression.*****//   
        //public static bool Promote(Employee emp)
        //{
        //    if (emp.Experience >= 5)
        //    {
        //        return true;

        //    }
        //    else
        //    {
        //        return false;
        //    }
        //}
    }
      delegate bool IsPromotable(Employee empl);

    class Employee
    {
        public int ID{get;set;}
        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public static void PromoteEmployee(List<Employee> employeeList,IsPromotable isEligibleToPromote)
        {
            foreach (Employee employee in employeeList)
            {
                if (isEligibleToPromote(employee))
                {
                    Console.WriteLine(employee.Name + ” Promoted”);
                    Console.ReadLine();
                }
            }
        }
    }
}


===================================================================
MULTICAST DELEGATES

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{

    public delegate void SampleDelegate();
    class Program
    { 

        
        public static void Main()
        {

            //SampleDelegate del1, del2, del3, del4;
            //del1 = new SampleDelegate(SampleMethodOne);
            //del2 = new SampleDelegate(SampleMethodTwo);
            //del3 = new SampleDelegate(SampleMethodThree);
            //del4 = del1 + del2 + del3;
            //del4();
            //Console.ReadLine();
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;
            del += SampleMethodThree;
            del();
            Console.ReadLine();
        }


        public static void SampleMethodOne()
        {
            Console.WriteLine(“Samplemethodone Invoked”);
            Console.ReadLine();
        }
        public static void SampleMethodTwo()
        {
            Console.WriteLine(“SamplemethodTwo Invoked”);
            Console.ReadLine();
        }
        public static void SampleMethodThree()
        {
            Console.WriteLine(“SamplemethodThree Invoked”);
            Console.ReadLine();

        }
       
    }
}


=====================================================================

Multicast delegates


A multicast delegate is a delegate that has references to more than one function.when you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.

There are 2 approaches to create a multicast delegate . depending on the approach you use
+ or += to register a method with the delegate
– or -= to un-register a method with the delegate.

Note: A multicast delegate, invokes the methods in the invocation list, in the same order in which they are added.

If the delegate has a return type other than void and if the delegate is a multicast delegate,
only the value of the last invoked method will be returned. Along the same lines, if the delegate has an out paraameters, the value of the output parameters, will be the value assigned by the last method.

Common interview question- where do you use multicast delegates?
Multicast delegate makes implementation of observer design patterns very simple. Observer pattern is also called as publish/subscribe pattern.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{

    public delegate int SampleDelegate();
    class Program
    { 

        
        public static void Main()
        {

            //SampleDelegate del1, del2, del3, del4;
            //del1 = new SampleDelegate(SampleMethodOne);
            //del2 = new SampleDelegate(SampleMethodTwo);
            //del3 = new SampleDelegate(SampleMethodThree);
            //del4 = del1 + del2 + del3;
            //del4();
            //Console.ReadLine();
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;
            int DelegateReturnedValue = del();
            Console.WriteLine(“DelegateReturnedValue= {0}”, DelegateReturnedValue);
           
            Console.ReadLine();
        }


        public static int SampleMethodOne()
        {
            return 1;
            Console.ReadLine();
        }
        public static int SampleMethodTwo()
        {
            return 2;
            Console.ReadLine();
        }
       
       
    }
}

Share this: