Showing posts with label .NET C# tutorial. Show all posts
Showing posts with label .NET C# tutorial. Show all posts

13 October 2018

difference between FirstOrDefault () and SingleOrDefault()

Recently one of my junior colleague working in .NET asked me about what is the difference between the FirstOrDefault and SingleOrDefault() methods.

Both FirstOrDefault() and SingleOrDefault() are the extension methods on the System.Collections.Generic.IEnumerable defined in System.Linq namespace.

The difference is pretty simple

Enumerable.SingleOrDefault()

SingleOrDefault() method returns the element which matches the condition. If no element matches the condition, then the method returns the default of value of the source type (default(TSource))

If more than one elements match the condition specified, it throw the Exception (InvalidOperationException) Enumerable.FirstOrDefault()

Enumerable.FirstOrDefault()

The way FirstOrDefault() method works is same as the Enumerable.SingleOrDefault() except that it doesn’t throw an exception if more than one element matches the condition. It just returns the first matching record.

How to choose between FirstOrDefault () and SingleOrDefault() methods?

If you know for sure that, there should only be one record present in the collection matching specified condition and presence of more than one record in the collection matching the condition indicates an error, then use the SingleOrDefault() method. So in error conditions, you will rightly get an exception.

If there could be multiple matching records for the specified condition in a collection and just you want the first one, then go ahead and use FirstOrDefault() method.

01 January 2018

what is const keyword in c# language

First, let's understand the English dictionary meaning of the "constant" word. Constant means "a situation that does not change", "not changing or varying", etc. Now having understood the meaning of constant, now let's understand about constant in C# language, how to define const in C# and when to use them?, etc

How to define constants in C#

Constant in C# language are defined using "const" keyword as in the below example.

public const double PI = 3.1415926535897931;

The π (PI) value in Mathematics is a constant and so the PI is defined as a constant in .NET framework class Math.

Characteritics of constants in C#

  1. Constant fields value should be assigned value when they are declared. You cannot declare constant fields in one place and assign a value to it another place. If you don't assign a value to a const field during their declaration, you will get a compilation error.

    A const field requires a value to be provided

  2. As obvious as it looks Once constants are defined, you cannot change the value of them. If you try to assign value to them you will get compilation error.
  3. System.Math.PI = 3.14;

    The above line of code which is trying to set a new value for Math.PI constant will result will produce a compilation error.

    The left-hand side of an assignment must be a variable, property or indexer

  4. Constant fields can be declared with any of the access specifiers depending upon your need. Thre is no restriction as such.

    They can be public, private, protected, etc

  5. When you assign a constant value to a variable, such assignment value will be replaced by actual value.

    For exmple, let's consider a class.

    double radius = 6.5;
    double areaOfCircle = Math.PI * Math.Pow(radius, 2);

    In the above code post compilation the constant variable PI will get replaced with its actual value. So after compilation code will look like below:

    double radius = 6.5;
    double areaOfCircle = 3.14 * Math.Pow(radius, 2);

Const keyword usage example

Below C# program defines two classes. Result and ResultHelper. Result class has 3 decimal type constants defined. ResultHelepr class is using the constatnts and determining whether a result is pass/fail.

public class Result
    {
        public const decimal DistinctionPercentage = 75;
        public const decimal FirstClassPercentage = 60;
        public const decimal PassPercentage = 35;

        public decimal Percentage { get; set; }
    }

    public static class ResultsHelper
    {
       public static void Display(Result result)
        {
          if (result.Percentage >= Result.DistinctionPercentage)
                Console.WriteLine("Pass. Distinction Class!!!.");

         else if (result.Percentage >= Result.FirstClassPercentage)
                Console.WriteLine("Pass. First Class!!.");

         else if (result.Percentage >= Result.PassPercentage)
                Console.WriteLine("Pass.");
          else
                Console.WriteLine("Fail.");
        }
    }

31 December 2017

readonly fields in C# class

C# language has a keyword to mention fields in a class can be readonly. In this tutorial let's discuss readonly keyword and how it can be used to convey class author intention that a field value shouldn't be modified once the class instance is created.

C# sample demonstrating readonly keyword

public class Employee
    {
        private readonly string _id;
        public string _deptId;

        public Employee(string id)
        {
            _id = id;
            DeptId = deptId;
        }

        public string ID
        {
            get
            {
                return _id;
            }
        }
        
        public string DeptID
        {
           get
             {
               return _deptID;
             }
           set
             {
              _deptID =value;
             }
         }
    }

Notes on above C# program

  1. "_id" has been declared as readonly.
  2. "_id" member has been assigned a value inside the Employee class constructor.

readonly class members and value assignment

  1. With readonly members properties, you can assign value only during initialization and inside the class constructors.
  2. If you try to assign value to members anywhere else, you will get the below error:

    A readonly field cannot be assigned to (except in a constructor or a variable initializer)

When to define readonly fields in a class

If a member of a class whose value you(class author) don't want anyone to change post object construction, then consider marking that member as readonly.

By declaring a member as readonly you are indicating to other fellow developers that such member value cannot be changed once the object is created (post constructor call).

10 November 2017

stop creating your own delegates, start using Action delegates

If you are still defining custom delegates, you can stop creating them. In place of them, you can use Action And Func delegates. Sounds cryptic!, don't worry, we will go into detail.

How we define custom delegates?

Delegates are function pointers, which are defined like below.

public delegate void ClickEventHandler (object sender, EventArgs args);

And then you will use the delegate to define an event.

public event ClickEventHandler Click = null;

So in practice, every time you need a new delegate to match the signature of the target method. In this way, you end up creating new delegates just to match the target method signatures. Creating custom delegates is no longer necessary in latest C# .NET, you easily use built-in Action Delegates.

Use Action delegates in place of custom delegates

The Click event can be defined using an Action delegate like below. Using Action delegate we can almost ALL the time stop worrying about creating new delegates. How cool is that!

public event Action<object, EventArgs> Click = null;

Now if you are wondering what are these Action Delegates, refer my another blog post on generic delegates.

18 May 2013

inheritance in oops

Inheritance is one of the main features of Object Oriented Programming concepts. Inheritance plays an important role in object oriented design. Let's go through the below sections to understand inheritance in OOPS:

What is Inheritance in OOPS?

Inheritance allows the derived classes to use features/functionality of the base class and also defines the relationships between the two objects. Code re-usability is one of the benefits of inheritance.

Inheritance examples in C# .NET

Best way to understand inheritance is to look at real-world examples. For instance in animal kingdom Homosepeans have characteristics of mammals. In OOPS terminology human beings are inherited from the mammals. So mammals are base class and human beings are derived class.

Let's consider a real-world inheritance example using the below C# class sample.

namespace InheritanceTutorial
{
  public class Doctor
  {
    public void DiagnosePatient() { }
    public void PrescribeMedicine() {}
  }
  
  public class Surgeon:  Doctor
  {
    public void DoSurgery() { }
  }
    
  public static void Main(string[] args)
  {

    Surgeon surgeon = new Surgeon();

     // Derived class instance invoking base 
     // class methods.
     // There by inheritance helps in code re-usability 
     // and also proper relationship 
     // between the classes.
     surgeon.DiagnosePatient();
     surgeon.PrescribeMedicine();

    surgeon.DoSurgery();
   }
}

Analogy of the above inheritance tutorial example:

  1. Doctor and Surgeon are two classes.
  2. Surgeon class inherits from the Doctor class. Here Doctor is base class and Surgeon is derived class.
  3. Derived class Surgeon is making use of the code present in the base class Surgeon. Derived classes customize base class behavior by overriding them or define new behaviors.
  4. Inheritance not just helps in code re usability. Using inheritance we can define "IS A" relationship.

Inheritance defines "IS A" relationship:

Considering the above inheritance example Surgeon IS A Doctor. Do not implement inheritance relationship for the sake of code re-usability. Always look out for IS A relationship. Your class design using inheritance makes sense only if every derived class exhibits IS A relationship with their base classes.

UML representation for OOPS inheritance:

In UML, OOPS inheritance will be represented by generalization relationship. In UML representation of inheritance, there a solid line running from derived class to base class with a closed arrowhead. Below UML diagram shows how to represent inheritance relationship between classes.

What do consider when implementing inheritance:

  1. Your proposed derived class should represent IS A relationship with the base class. If there is NO IS A relationship, then inheritance is not the right option. Don't try to fit the inheritance everywhere.
  2. Depth of Inheritance indicates how many classes are present in its inheritance hierarchy. It would be difficult to maintain the code if your inheritance class hierarchy chain is very long.
  3. Inheritance is static in nature, unlike polymorphism. At design time only, the relationship between the base class and derived class is fixed. And the behavior what derived class exhibits is also fixed.

Design pattern based on Inheritance:

Template method design pattern makes use inheritance. Derived classes in Template design pattern customize one or more algorithm steps behavior, which are defined in the base class.

13 May 2013

prerequisite for C# .NET "using" keyword

Prerequisite for "using" keyword:

To use "using" keyword, the class has to implement the IDisposable interface. If not there will be compile time error.

class Program
{
  public static void Main(string[] args)
  {
  using (ClientManager clientManager = new ClientManager())
    {
     // Your logic
    }
  }
}
When you compile the above code, you will get the below compile time error:

"type used in a using statement must be implicitly convertible to 'System.IDisposable'."

This is because ClientManager has not implemented the IDisposable interface.

Resolving the compile time error:

When the class ClientManager implements the System.IDisposable compile time error will disappear. Then ClientManager class can be used inside the using statement.

public class ClientManager:  IDisposable 
{
 public void Dispose()
  {
    // Your class dispose logic
  }
}

More on C# .NET using keyword

You can refer one more interview question on C# .NET "using" keyword.

03 November 2012

.net c# memory allocation for reference types

One of my buddy who also works on .NET attended an interview recently. In one of the rounds of technical discussion, he was asked an interesting question on memory allocation for reference types.

What is the output of the below program?

namespace MemoryAddressForReferenceTypeParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employeeObject = new Employee();
            Process(employeeObject);
        }
        private static void Process(Employee employeeObject)
        {
            // Set null to reference type parameter
            employeeObject = null;
        }
    }
    public class Employee
    {
    }
}

Looking at the code above I said to my friend that its throws System.NullReferenceException. But actually it doesn't throws any exception and the program writes "MemoryAllocationForReferenceTypes.Employee" to the console and gracefully exists.

For a moment I and my friend were wondering what's happening. Later we realized the fact that, even when reference type variable is passed to a method, the method argument will is altogether a different variable, but its also pointing to the same memory location where employee object is stored.

The analogy:

  1. Setting null to the method argument inside the Process() method, just removed the one more reference created to the memory location where employee object is stored on the heap.
  2. But the original employee object is still there on the memory intact and employee variable in the Main method still pointing the same memory location where employee object is stored.
  3. Hence ToString() method doesn't throw System.NullReferenceException and it prints the Employee class full name which is expected out the default ToString() method implementation.

But we didn't stop here. And used the ref keyword while passing the parameter value to the Process() method.

namespace MemoryAddressForReferenceTypeParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employeeObject = new Employee();
            Process(ref employeeObject);
        }

        // Now used ref keyword while passing the parameter
        private static void Process(ref Employee employeeObject)
        {
            // Set null to reference type parameter
            employeeObject = null;
        }
    }
    public class Employee
    {
    }
}

Since ref keyword is used while passing the value to the Process() method, it doesn't create a different variable to point to the same memory location where employee object is stored and hence setting the null to the employee variable will reflect the employee variable present in the Main() method as well. Now, the employee object is null and it throws the System.NullReferenceException.