Menu Close

Blog

Slide 1

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

Slide 2

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

Slide 3

Microsoft Business Applications Blogposts, YouTube Videos and Podcasts

Helping Businesses with Technology

previous arrow
next arrow

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:

MULITPLE CLASS INHERITANCE USING MULTIPLE INTERFACES

MULITPLE CLASS INHERITANCE USING MULTIPLE INTERFACES


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

namespace ConsoleApplication4
{
    interface IA
    {
        void AMethod();
    }
    class A : IA
    {
        public void AMethod()
        {
            Console.WriteLine(“A”);
        }
    }
    interface IB
    {
        void BMethod();
    }
    class B : IB
    {
        public void BMethod()
        {
            Console.WriteLine(“B”);
        }
    }
    class AB : IA,IB
    {
        A a = new A();
        B b = new B();
        public void AMethod()
        {
            a.AMethod();
        }
        public void BMethod()
        {
            b.BMethod();
        }
    }
    
    class Program
    {
        public static void Main()
        {
            AB ab = new AB();
            ab.AMethod();
            ab.BMethod();
            Console.ReadLine();
        }
    }
}

Share this:

MULTIPLE CLASS INHERITANCE PROBLEM IN C#

MULTIPLE CLASS INHERITANCE PROBLEM IN C#

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

namespace ConsoleApplication4
{

    /// <summary>
    /// 
    /// PROBELMS WITH MULTIPLE CLASS INHERITANCE
    /// </summary>
    class A
    {
        public virtual void print()
        {
            Console.WriteLine(“class A implemented”);
        }

    }
    class B : A
    {

        public override void print()
        {
            Console.WriteLine(“Class B overriding print() method”);
        }

    }

    class C : A
    {
        public override void print()
        {
            Console.WriteLine(“Class C overriding print() method”);
        }
    }
    class D : B, C
    {


    }
    class Program
    {
        public static void Main()
        {
            D d = new D();
            d.print(); // AMBIGUITY HERE, WHICH METHOD WILL IT EXECUTE, SO A DIAMOND PROBLEM.
        }
    }
}
Share this: