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

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods