Monday, June 24, 2019

Difference between Interface and Delegate in c#


Interface is a contract, a method declared inside of interface, class which implementing that Interface should provide definition for declared method inside interface.

In case of delegate, if a class (let's say A) method needs callback function as a parameter or exposing a delegate (same like event) to subscribe. you need to implement callback method with same signature as delegate to subscribe delegate/callback.

In both cases (in case of interface and in case of delegate) you need to define a method with declared signature by interface/delegate so, in case of single method interface seems there is no difference between interface and delegate.

let's dig in detail,

  • for an interface method implementation, it's necessary to declare it public.
  • if interface has more than one method, implementer of interface need to define all the methods of interface.
  • we can subscribe a private method, or anonymous method to delegate, which is not possible in case of interface.
  • In case of interface, we need to define method same as method declared in interface (same name) but in case of delegate we can assign any method whose signature is same as delegate signature.
  • delegate provide multicast functionality, we can subscribe multiple methods to delegate but not to interface.
* Please let me know your comments...

Tuesday, June 4, 2019

WPF : C# Async methods



Below example shows how to create and use async methods in WPF application.
In below example, There are two ways to create void returning async method as well string returning
Async method.

you can copy and paste relevance code in any new WPF application and check it's functionality(mainly responsiveness). I tried to create long running operations and application responsiveness during long running operation.



.CS File

 public partial class AsyncWithWPF : Window
    {

        string strGlobalVariable = "";
        public AsyncWithWPF()
        {
            InitializeComponent();
        }
     
        private async void BtnAsyncReturnVoid1_Click(object sender, RoutedEventArgs e)
        {
            lblResult.Content = "";
            lblResult.Content += " Starting..  ";
            await LongRunningTaskReturnvoid1();
            lblResult.Content += "Finished LongRunningTaskReturnvoid1() " + strGlobalVariable;
        }
        public Task LongRunningTaskReturnvoid1()
        {
            lblResult.Content += "   inside LongRunningTaskReturnvoid1() ";
            return Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                strGlobalVariable += " Async Task has finished ";
            });
        }
        private  void BtnAsyncReturnVoid2_Click(object sender, RoutedEventArgs e)
        {
         
                lblResult.Content = "";
                lblResult.Content += " Starting..  ";
                LongRunningTaskReturnvoid2();
           
            lblResult.Content += "after LongRunningTaskReturnvoid2() call";
        }
        public async void LongRunningTaskReturnvoid2()
        {
         
                await Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
             

            });
                lblResult.Content += "  finished LongRunningTaskReturnvoid2()";
           
        }
        private async void BtnAsyncReturn1_Click(object sender, RoutedEventArgs e)
         {
            string result = "";
            lblResult.Content = "";
            lblResult.Content += " Starting..  ";
            try
            {
                result = await LongRunningTask();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Handled");
            }
            lblResult.Content += result +" Finished LongRunningTaskvoid()";
         
        }
        public Task LongRunningTask()
        {
            lblResult.Content += "   inside LongRunningTask() ";
            return Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000); //throw new Exception("test");// uncomment to check exception handling.
                return "Hello";
            });

        }
     
        private void BtnTestResponsiveness_Click(object sender, RoutedEventArgs e)
        {
              MessageBox.Show("Hello");
        }
   

    }

C# : Protected Members



Protected is a keyword in C#, used to define accessibility for class members like variables, properties and methods, etc.
protected members have similar accessibility as private member with only one difference that are also available in derived classes.

Note: for a class that is defining protected member and it's derived classes, they are available as private i.e. class defining protected member and it's derived classes are not able to access protected member via it's object, while any other public or protected member can use that newly defined protected members. please see below example:

class BaseClass
    {
        protected int Add(int a ,int b)
        {
            return a + b;
        }
        protected void AddWrapper()
        {
           Console.WriteLine( Add(5, 9));
        }
  }
  
class DerivedClass : BaseClass
    {
        public void m1()
        {
            int k = Add(4, 5);
            Console.WriteLine("Calling BaseClass's protected methods via Wrapper method m1()");
            AddWrapper();
        }
}

public class Tester
    {
        public static void Main()
        {
            BaseClass obj1 = new BaseClass();
            // not able to call Add method via BaseClass object.
            DerivedClass obj2 = new DerivedClass();
            obj2.m1();
            Console.Read();

        }
}




C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...