Skip to main content

C# Cheat Sheet : Part 1

Constructors

Constructors are used to Initialize the objects, parameters when the object is getting initialized, 

Constructors can be of type


  • Public
  • Private
  • Protected 
  • Internal
  • Protected Internal
  • Static 
Public Constructors

This type will be instantiated every time the new operator is used for the class or struct,

Typically constructors will be without any parameters,

For Example 



Class Cls = new Class(); 

but this will not be the case always, you can instantiate the class by practically any number of arguments

Private Constructors

If the programmer doesn't want a particular class to be instantiated but wants the client code to use the class members then the programmer may set the constructor to be private

Example Program:

The following program generates the number of desired GUIDs, and the class initialization is freezed by private constructor

    public class StringAppend
    {
        private StringAppend()
        {

        }       
        public static int NumberOfGUIDs;
        public static StringBuilder SbGUID = new StringBuilder();
        public static string GetGUIDs()
        {
            string returnValue = string.Empty;
            for (int LocalCounter = 0; LocalCounter < NumberOfGUIDs; LocalCounter++)
            {
                SbGUID.AppendLine(Guid.NewGuid().ToString());
            }
            returnValue = SbGUID.ToString();
            return returnValue;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the Number of GUIDs you want");
            StringAppend.NumberOfGUIDs = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(StringAppend.GetGUIDs());
            Console.ReadLine();
        }

    }


In .NET we have Console, Math classes with private constructors

Protected Constructors


Lets see the following simple program which have two classes ClassA and ClassB


ClassA is the base class and ClassB is the derived class from ClassA





    public class ClassA
    {
        protected ClassA()
        {
            Console.WriteLine("Protected Constructor for ClassA is called!");
        }
    }
    public class ClassB : ClassA
    {
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            ClassA ClsA = new ClassA();
          
            Console.ReadLine();
        }

    }

Note we have specified the constructor as Protected and when compiling we got the compiler error as

"ProctectedContructors.ClassA.ClassA()' is inaccessible due to its protection level"

If we slightly change the code like this,

ClassB ClsB = new ClassA();

Even this won't work, we will get the same access deficiency error


Then if we change like this ClassB ClsB = new ClassB();



  public class ClassA
    {
        protected ClassA()
        {
            Console.WriteLine("Protected Constructor for ClassA is called!");
        }
    }
    public class ClassB : ClassA
    {
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            //ClassA ClsA = new ClassA();
            //ClassB ClsB = new ClassA();

            ClassB ClsB = new ClassB();
          
            Console.ReadLine();
        }
    }


This will work and the output produced is 

"Protected Constructor for ClassA is called!"

If we add the code in the ClassB



        public ClassB()
        {
            Console.WriteLine("Public Constructor for ClassB is called!");


        }

Output:

"Protected Constructor for ClassA is called!
Public Constructor for ClassB is called!"


Internal Constructors



Internal keyword is used to limit the access of a member to the residing assembly only, 


based on this we have a sample code




 public class ClassA
    {
        internal ClassA()
        {

        }
    }

    public class ClassB : ClassA
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            ClassA ClsA = new ClassA();           
        }

    }


This will perfectly work, as the object creation is within the same assembly



So we will extend our program to show the more usability of this constructor


We write a separate "Class Library" and write a class in that 



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

namespace BaseClassLib
{
    public class Example1
    {
        internal Example1()
        {

        }
    }
}


So we are referencing the "Class Library" project "BaseClassLib" to our program 




using BaseClassLib;


Then write the code in the main function 

BaseClassLib.Example1 Ex1 = new Example1();


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

using BaseClassLib;

namespace InternalConstructors
{
    public class ClassA
    {
        internal ClassA()
        {

        }
    }

    public class ClassB : ClassA
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            //ClassA ClsA = new ClassA();           
            BaseClassLib.Example1 Ex1 = new Example1();
        }
    }
}

Here you will get the compiler error message as "No Constructor is defined", hence we are restricting the object creation to the internal members only, this will useful in securing the application from unwanted access / initialization 

Using of internal constructors will be huge in case if you are exposing the DLLs to client code and you don’t want the client code to access / initialize the objects outside of your assembly.

Example:

For Sales Forecast DLL, you may want the client code to create the object for the class SalesForeCast and access the members like GenerateSalesForeCast, DeleteCurrentSalesForecast…

But you don’t want the client code to access / initialize objects to crucial details like credential manager, service manager, authentication keys details

Protected Internal

We already have seen how the protected constructor works and internal constructor works, combining both will provide the usage of the Protected Internal Constructors,

The Base assembly will not have the privilege to instantiate the objects, but the derived assembly can have the access

(To be Continued)

Comments

Popular posts from this blog

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven