Thursday, August 8, 2024

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 class or struct declaration. 

There are two ways to declare records 

public record class Person(string FirstName,  int Age);

or we can define properties explicitly like

public record class Person{

    public string Name{get;set;}

    public int Age{get;set;}

}

var p1=new Person("Niranjan", 30);

var p2=new Person("Niranjan",30)

if we will compare p1 and p2 ,it will return true.

if(p1==p2) //true ; while in case of class it will return false.

Points to remember:

  • If records declared with primary constructor syntax, they will be immutable. we can change properties and get new record instance using 'with' keywords.
  • record overides ToString(),ToEqual(), GetHashCode() and implements destructing.
  • using .ToString with records prints all properties with name and value.
  •  record overriddes ToEqual() methods uses IEquatable<T> interface to compare preparties values so it's necessary to use property datatype which implements IEquatable<T> in order to get successful value comparison for two records.
Example:

public records class Employee(string Name, int Age, List<string> Addresses);

var e1=new Employee("Raj",30,new List<string>{"A1","A2"});
var e2=new Employee("Raj",30,new List<string>{"A1","A2"});

if(e1==e2) // will return false as List<string> does not implement IEquatable<T> interface. 

Saturday, July 20, 2024

difference between Pub/Sub and observer pattern

The purpose of the Publish/Subscribe pattern is the same as the Observer pattern: you want to notify other services when certain events take place. But there is an important difference between the Observer and Pub/Sub patterns. In the observer pattern, the broadcast is performed directly from the observable to the observers, so they "know" each other. But when using a Pub/Sub pattern, there is a third component, called broker, or message broker or event bus, which is known by both the publisher and subscriber. Therefore, when using the Pub/Sub pattern the publisher and the subscribers are precisely decoupled thanks to the mentioned event bus or message broker.

Thursday, May 16, 2024

Difference between First, FirstOrDefault, Single, SingleOrDefault

 

See the below example I am adding 4 items to list with 1 duplicate and calling these methods, output written with comments side by method call.

            Base b1 = new Base() { Id = 1, Name = "base1" };

            Base b2 = new Base() { Id =2, Name = "base2" };

            Base b3 = new Base() { Id = 3, Name = "base3" };

            List<Base> lst = new List<Base> { b1, b2, b3, b1 };

            Base b4 = new Base { Id = 4, Name = "base4" };

            var findfirst= lst.Find(x => x.Id == 9);

            var firstElement = lst.First(x => x.Id == 9);//exception

            var firstOrDefaultTest = lst.FirstOrDefault(x => x.Id == 90); //null, default value;

            var singleOrdefaulttest = lst.SingleOrDefault(x => x.Id == 1);// exception because found more than 1 element for Id=1. no exception In-case not found.

            var singleTest = lst.Single(x => x.Id == 90);//exception if not found also if found duplicate.

Something about List item reference

     // Some differenent example 


            Base b1 = new Base() { Id = 1, Name = "base1" };

            Base b2 = new Base() { Id =2, Name = "base2" };

            Base b3 = new Base() { Id = 3, Name = "base3" };

            List<Base> lst = new List<Base> { b1, b2, b3 }; //b1 ,b2, b3 added to list

            Base b4 = new Base { Id = 4, Name = "base4" };

            PRintList(lst);


            var first= lst.Find(x => x.Id == 1); // fetching first item and chaging it by assigning new item.

            first = b4; //it will not affect list item

            PRintList(lst);

            

            lst[0] = b4; // now lost[0] will be b4.

            PRintList(lst);



            void PRintList(List<Base> lst)

            {

                foreach(Base b in lst) Console.WriteLine(   b.Id +" -"+ b.Name);

            }


            //Output:

            //1 - base1

            //2 - base2

            //3 - base3


            //1 - base1

            //2 - base2

            //3 - base3


            //4 - base4

            //2 - base2

            //3 - base3

Sunday, May 12, 2024

Null conditional Operator, Null Coalescing Operator, Null Forgiving Operator in C#

  

Null Conditional Operator (?): Generally used with Object reference variable before accessing any property of that object, it checks that if object is null then it will return null without accessing any property of that object and prevent from object reference exception. for example,

var customerName = objCustomer?.Name ;

Above expression return null if objCustomer is null without accessing Name property of Customer.

Null-Coalescing Operator (??): If applied variable is null then it will return right hand side given value else it will return value of variable. for example,

var customerName=objCustomer?.Name?? "Not Found";

If customer has no value (null) for its name, then above expression will return "Not Found" else name of customer.

Null Forgiving Operator (!): If Nullable enabled in project file means you are using null state analysis feature for framework, which allow you to define reference type either nullable or non- nullable.  If non nullable reference type contains null compiler will generate warning. sometimes we know that this variable is nullable variable, and it has non null value, but compiler still force you to check for null, in this case you can use (!) null forgiving operator to tell that I know it's not null, don't generate warning. 

 Product?[] products = Product.Get(); 

 var productName= products[0]!.Name ;

Note: You can disable null state analysis on specific file by using " #pragma warning disable CS8602.


How to declare Nullable reference type in c#

 A variable of type Product?[] denotes an array that can contain Product or null values but that won’t be null itself:

Product?[] arr1 = new Product?[] { p1, p2, null }; // OK

Product?[] arr2 = null; // Not OK

A variable of type Product[]? is an array that can hold only Product values and not null values, but the array itself may be null:

Product[]? arr1 = new Product[]? { p1, p2, null }; // Not OK

Product[]? arr2 = null; // OK

A variable of type Product?[]? is an array that can contain Product or null values and that can itself be null:

Product?[]? arr1 = new Product?[] {p1, p2, null }; // OK

Product?[]? arr2 = null; // Also OK


Sunday, May 5, 2024

Using SortedList in C#

Sorted list in C# is a collection of Key-Value pairs, Values are accessed via Key or by Index. It's generic so we can choose any datatype for Key. Key must be unique while we can have duplicate values. Key are sorted automatically, due to this it's a bit slower as compared to HashTable or Dictionary.

Removing or adding a item in sorted list will change index of items as it will sort keys.

Below are some important methods exposed by SortedList. 

        public TKey GetKeyAtIndex(int index);

        public TValue GetValueAtIndex(int index);

        public int IndexOfKey(TKey key);

        public int IndexOfValue(TValue value);

public void SetValueAtIndex(int index, TValue value);

Example: Copy and paste below code in VSCode/VisualStudio

 public static void WorkingWithSortedList()

        {

            //Soreted list is a collection of sorted key value pair.

            // data can be accessed via key or index.

            var list = new SortedList<int, string>();

            list.Add(1, "One");

            list.Add(2, "Two");

            list.Add(3, "Three");

           // list.Add(2, "Two"); //Duplicates are not allowed.

            list.Add(5, "Five");

            list.Add(6, "Six");

            list.Add(4, "Four");//Adding at last but it would get added at index (3);

            list.Add(7, "One"); // Duplicate values are allowed!

            Console.WriteLine(list.Count);

            Console.WriteLine("Accessiing sorted list elements");

            //Below loop will print item which is Key-value pair object

            foreach (var item in list)

            {                Console.WriteLine("Sorted list is a collection of KeyValue :" + item);            }

           foreach (var item in list)  

          {          Console.WriteLine($"item Key={item.Key}, Value={item.Value}");            }

            for(int i = 0; i < list.Count; i++)  {

                Console.WriteLine($"Item at index {i}={list.GetKeyAtIndex(i)} ,{list.GetValueAtIndex(i)}");

            }

            //Chning item for key=2

            list[2] = "Two Changed";

           foreach (var item in list)        {

                Console.WriteLine(item);

                Console.WriteLine($"item Key={item.Key}, Value={item.Value}");

           }

            Console.WriteLine(  "Getting index of last added item i.e.4");

            Console.WriteLine( list.IndexOfKey(4));

            Console.WriteLine("Getting index of value Four");

            Console.WriteLine(list.IndexOfValue("Four"));

            Console.WriteLine("Index of above key-value would get changed as removing itewm from index 2");

             list.Remove(2); //removed item by key;

             Console.WriteLine("Getting index of last added item i.e.4");

            Console.WriteLine(list.IndexOfKey(4));

            Console.WriteLine("Getting index of value Four");

            Console.WriteLine(list.IndexOfValue("Four"));

            Console.WriteLine(  "***********Prining Keys ****************");

            foreach(var key in list.Keys) { Console.WriteLine(key); }

            Console.WriteLine("***********Prining Values ****************");

            foreach (var val in list.Values) { Console.WriteLine(val); }

            Console.WriteLine(" WHat if trying to access key which is not present");

         //   Console.WriteLine(list[8]); // Thow exception as no item at index 8

        }

Friday, March 1, 2024

C# : Merge two sorted array

 int [] first=new int[]{1,3,5,9,11,15};

int [] second=new int[]{2,4,6,8};  

int n1=first.Length, n2=second.Length;
int [] third =new int[n1+n2];
Console.WriteLine($" n1={n1} and n2={n2}");
int i=0,j=0,k=0;

// Logic
// ==>i=0;j=0 =>1
// i=1,j=0 =>2
// i=1,j=1=>4
// i=1, j=2 => 5
// i=2, j=2 ==>6
// i=2, j=3 ==>8
// i=2,j=4 ==> exit lpoop ==>

while(i<n1 &&j<n2){  
    Console.WriteLine($" i={i} , j={j}, k={k}");
    if(first[i]>second[j]){
        third[k++]=second[j++];      
    }
    else{
        third[k++]=first[i++];        
    }    
}
while(i<n1){
    third[k++]=first[i++];
}
while(j<n2){
    third[k++]=second[j++];
}
foreach (var item in third)
{
    Console.WriteLine(item +"--");
}

Friday, July 2, 2021

Difference between object and dynamic in c# | Object Vs Dynamic

As we know that object is a base class for the the types in c# i.e. object is a class and all the classes in .net framework derived from object. we can assign any value (either ValueType or ReferenceType) to object, similarly we can assign any value to the dynamic. but there are few difference in dynamic and object 
  • dynamic is not a type it's just a keyword which tells compiler to ignore compile time type checking and infer dynamic declared variable's type at runtime.
  • when you assign a value to dynamic variable and then you assign this variable's value to another variable who's type is similar to assigned value's type you don't need type casting (see the example below) but in case of object you need to type caste object variable to particular type otherwise you will get compile time error.
      public static void ObjectVsDynamic()
        {
            dynamic a = "hello";
            string str = a; // no casting
          
            Console.WriteLine(str);

            object b = "hello";
            string str1 = (string)b;// in case of object explicit casting required.
            Console.WriteLine(str1);
            Console.ReadLine();
        }

Tuesday, June 2, 2020

ASP.NET Core 3.0 (C# ) : Send email via outlook host

Below code shows how to send email via outlook host using SMTP client in C#

     public interface IOutlookMailClient
    {
        void SendMail(string recipient, string subject, string message);
    }

public class OutlookMailClient : IOutlookMailClient
    {
        private readonly string sender;
        private readonly string password;
        private readonly string host;
        private readonly int port;
        private readonly OutlookMailServiceOptions emailOptions;
        private readonly ILogger<OutlookMailClient> logger;
       
public OutlookMailClient(IOptions<OutlookMailServiceOptions>                   mailOptions,ILogger<OutlookMailClient> logger)
        {
            this.emailOptions = mailOptions.Value; ;
            this.password = emailOptions.Password;
            this.host = emailOptions.Host;
            this.port = emailOptions.Port;
            this.sender = emailOptions.Sender;
            this.logger = logger;
        }
        public void SendMail(string recipient, string subject, string message)
        {
            logger.LogInformation("Enter : OutlookMailClient.SendMail");
            logger.LogInformation("Mail recipient :" +recipient +" Subject : "+subject);
            SmtpClient client = new SmtpClient(host);//new SmtpClient("outlook.office365.com");
            client.Port = port;
            //client.Port = 587;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            System.Net.NetworkCredential credentials =
            new System.Net.NetworkCredential(sender, password);
            client.EnableSsl = true;
            client.Credentials = credentials;
            try
            {
                var mail = new MailMessage(sender.Trim(), recipient.Trim());
                mail.Subject = subject;
                mail.Body = message;
                client.Send(mail);
                logger.LogInformation("Exit : OutlookMailClient.SendMail");
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                throw ex;
            }
        }
    }
}

IOptions<OutlookMailServiceOptions> is a asp.net core feature to read data from appsetting.json using a model. here OutlookMailServiceOptions is a POCO class used to keep mail settings from Json config file. you can use any alternative if you are not using asp.net core.

 public class OutlookMailServiceOptions
    {   
            public string Sender { get; set; }
            public string Host { get; set; }
            public int Port { get; set; }
            public string Password { get; set; }
    
    }
put this configuration in appsetting.json

"OutlookMailServiceOptions": {
    "Sender": "sender mail id",
    "Host": "outlook.office365.com",
    "Port": 587,
    "Password": "your password"
  }

Now you have to call this api in your code, to call first you need to inject this api via dependency injection in ConfigureService method of Startup.cs like :

 services.Configure<OutlookMailServiceOptions>(Configuration.GetSection(nameof(OutlookMailServiceOptions))).AddSingleton(x => x.GetRequiredService<IOptions<OutlookMailServiceOptions>>().Value);

            services.AddScoped<IOutlookMailClient, OutlookMailClient>();

Now, you can inject this API in your Controller via constructor :

private readonly IOutlookMailClient emailClient
DefaultController (IOutlookMailClient emailClient) //Constructor
{
this.emailClient=emailClient;
}
 
//mail api injected , now simply call sendMail() method from any method like:

  emailClient.SendMail("To mail address", "Subject", "Body");

All the other required details (Sender, Host, Port, etc.) to send mail, API will read from AppSetting.Json via IOption mechanism.

Friday, February 21, 2020

Multi Threading in C# : Returning a value from thread via shared variable.


Objective : We want to perform a long running operation in a separate thread and want result back from that thread.To achieve this we can use a shared/global variable,  thread will perform desired operation and then update global variable. please see below example for more clarity:

Note : variable and method used in below program is static, because we want to call them inside Main() which is static method.

 public class Program
  {
      static int resultFromThread = 0;
      #region Returing value from Thread

      public static void Main()
      {
          // if we want to call method with multiple paramter, we can use lambda expression to pass params to thread, like:

          Thread child = new Thread(() => Add(5, 4));
          child.Start();
          
          // some dummy operation performed by main
          for (int i = 0; i < 10; i++)
          {
              Thread.Sleep(100);
              Console.WriteLine("Some opeation performed by Main, side by side Child is doing it's own opeartion");
          }

          child.Join(); // Main will wait until child thread finished.
          Console.WriteLine("Child Thread has finished it's operation, now we can check resultFromThread");
          Console.WriteLine("value of resultFromThread "+ resultFromThread);
          Console.Read();

      }
      public static void Add(int a, int b)
      {
          Thread.Sleep(3000); //pausing thread for 3 sec.and then updating global variable resultFromThread.
          resultFromThread= a + b;
      }
      #endregion
  }

Multi Threading in C# (using Thread class)


MultiThreading in C# : Now a days multiple ways we have to create thread in C#, Thread class is present in
C# from inception.Thread class takes a ThreadStart/ParameterisedThreadStart delegate, or simply we can pass a parameterised or non parameterised method which returns void.
In case of parameterised method we can pass a single parameter of type Object.
Please see the below example for more clarity:

public class Program
    {
        static void Main(string[] args)
        {
            // calling non-parameterised method in Thread class 
            Thread child = new Thread(ThreadOperation);
            child.Start();

            // calling parameterised method in Thread class 
            Thread paramterisedChild = new Thread(ThreadParamterisedObject);
            paramterisedChild.Start("Niranjan"); //--- Any object we can pass to thread---//

            // additional work done by main thread
            for(int i=0;i<10 font="" i="">
                Thread.Sleep(500); //**** pausing thread for 500 milisecond.****//
                Console.WriteLine(" Main Thread " + i);
            }
            Console.WriteLine(" Good bye from Main");
            Console.ReadLine();
        }
        //---This method will be called by child thread---.
        public static void ThreadOperation()
        {
            for (int i = 0; i < 10; i++){
                
                Thread.Sleep(500); //**** pausing thread for 500 milisecond.****//
                Console.WriteLine(" Child Thread " + i);
            }
        }
        //---This method need one paramter of type object---.
        public static void ThreadParamterisedObject(object obj)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(500); //pausing thread for 500 milisecond.
                Console.WriteLine(" Child Thread " + obj.ToString());
            }
        }
    }



Sunday, January 12, 2020

C# Palindrome Program


A palindrome is a word, phrase, number or sequence of words that reads the same backward as forward. For Example Madam, Nitin, RAGGAR etc.
below is a C# program which checks given string is palindrome or not:

program logic : suppose we have a string of length 5, we will check first char of string is equal to last char of string, second char of string is equal to second last char of string and so on. like
char[0]==char[4]
char[1]==char[3]
char[2]==char[2]
if all matched then string is palindrome.

        public static void IsPalindrome(string s)
        {
          
            char[] cArr = s.ToCharArray(); // Converting string to char array
            bool isPalindrome = true; //a flag 
            
            for (int i = 0; i < s.Length / 2; i++)
            {
               // Console.WriteLine("Iteration i=" + i);// to get iteration count

                if (cArr[i] != cArr[(s.Length - 1 - i)])
                {
                    isPalindrome = false;
                    Console.WriteLine("Not Palindrome");
                    break;
                }
                
            }
            if (isPalindrome)
            {
                Console.WriteLine("Palindrome");
            }

        }


Friday, July 26, 2019

WPF : How To Set Focus on another window (MVVM)


 How To Set Focus on another window (MVVM)?

I have two window (Parent-Child). Parent window opens Child window so child window is focused
(i.e. top most window) but when child replies to Parent, Parent window is not focused (i.e. it's not on top).

I have created a attached property in a separate class like:

class FocusAttched:DependencyObject
    {
        public static DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusAttched),
                new UIPropertyMetadata(false, OnIsFocusedChanged));
        public static bool GetIsFocused(DependencyObject dependencyObject)
        {
            return (bool)dependencyObject.GetValue(IsFocusedProperty);
        }
        public static void SetIsFocused(DependencyObject dependencyObject, bool value)
        {
            dependencyObject.SetValue(IsFocusedProperty, value);
        }
        public static void OnIsFocusedChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            ((FrameworkElement)dependencyObject).Focus(); //My Code-Niranjan
           
            // Removing hard coding
            //TextBox textBox = dependencyObject as TextBox;
            //bool newValue = (bool)dependencyPropertyChangedEventArgs.NewValue;
            //bool oldValue = (bool)dependencyPropertyChangedEventArgs.OldValue;
            //if (newValue && !oldValue && !textBox.IsFocused) textBox.Focus();
        }
    }

Now Attached this property to Parent window control (textbox)

                      VerticalScrollBarVisibility="Visible" TextWrapping="Wrap" AcceptsReturn="True" HorizontalAlignment="Left"
                 Height="248" Margin="191,36,0,0"   VerticalAlignment="Top" Width="249"/>


I am binding this attached property with a new property in View Model, for this reason I am creating a new bool property in View model.

bool _setFoucs;
        public bool SetFocus {
            get { return _setFoucs; }
            set { _setFoucs = value; OnPropertyChanged(nameof(SetFocus)); }
        }

I will set this property in Callback method.

Summery : Idea is that when Child window sends a message to Parent window, callback method will get called by Child, in this Callback I am setting this 'SetFocus' Property which is attached to TextBox of Parent window, OnPropertyChnage callback of Attached/Dependency property I am calling Focus() method of FrameworkElement( TextBox is Framework element).

Thursday, July 25, 2019

WPF - Difference between ContentControl and ContentPresenter?



Difference between ContentControl and ContentPresenter?


ContentPresenter is a lightweight element. It's derived from FrameworkElements class. So, It has no Template property (i.e.) we can't set control Template for it, while we can set data template for it as it has Content property.

ContentPresenter has a addition property 'ContentSource' which is not present in Content Control.

Default value of 'ContentSource' property is content, So when we will put ContentPresenter inside of ControlTemplate we don't need to define binding explicitly.

ContentControl also uses ContentPrenseter in it's template to display data.

WPF - How to print Parent hierarchy of an element?



How to print Parent hierarchy of an element?

            DependencyObject _parent = myGrid.Parent;
            while (_parent != null)
            {
                System.Diagnostics.Debug.WriteLine(_parent);
                _parent = ((FrameworkElement)_parent)?.Parent;
            }

Every framework element has a Parent property, we can loop through like above code and print parent of particular element.

Tuesday, July 2, 2019

WCF : How to transfer large data via wcf service?


How to transfer large data from wcf service?

To transfer large data from wcf service, we need to change some configuration settings like:

MaxReceivedMessageSize
Transfer Mode
Max Depth (in ReaderQuotas)
MaxArrayLength

Above are necessary settings to transfer large data form WCF, apart from these settings, to increase performance you can change message encoding to "MTOM".

Complete binding configuration is :
 

    

Note : you need these settings in both Service and application config file (web.config and app.config).






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 ...