Expression-bodied Members in C#

Expression-bodied members are one of the shiny features of C# 6.0 which allows us to write the implementation of a member in more readable and concise format. We can use the expressions as a definition of the members instead of using the statement block. The format of the expression is as

var=> expression

This is also called lambda expressions and => is called lambda operator. In C# 6.0, we can use this feature with methods and properties. Lets see few examples

Properties: Instead of using the normal getter, we can use expressions with lambda operators as mentioned.


// Normal way
public string FullName
{
    get { return string.Format("{0} {1}", FirstName, LastName); }
}

// Using Expression (C# 6.0)
public string FullName => string.Format("{0} {1}", FirstName, LastName);

// Above code can be more consize using string interpolation
public string FullName =>$"{FirstName} {LastName}";

If you are not aware of String Interpolation, you can refer one of my previous post here.

Methods : Similar to properties, C# 6.0 also allows us to use expressions while writing methods which returns values to the caller.


// Normal way
public string GetFullName(string firstname, string middleName, string lastName)
{
    return middleName == null ? $"{firstname} {lastName}" : $"{firstname} {middleName} {lastName}";
}

// Using Expessions 
public string GetFullName(string firstname, string middleName, string lastName) => middleName == null ? 
             $"{firstname} {lastName}" : $"{firstname} {middleName} {lastName}";

Limitation: There is a limitation of expression bodied members.We can have just single statement in the expression and statement blocks {} are not allowed. In my above example, I used the ternary operator conditional logic instead of using if statement block.

As we can see C# 6.0 added the capability for methods and read only properties, C# 7.0 added more power to this feature and now we can use expressions in constructors, set accessors in properties, indexers and finalizers. Let’s take a look

Properties: We saw earlier enhancements for Property which was similar to get accessor

private string _name;
public string Name {
    get => _name;
    set => _name = value;
}

Here this is a very simple example and in this scenario, I would like to prefer the Auto propery as below

public string Name { get; set; }

However in my earlier example where I was returning FullName after concatenating two strings, there it is better suited. So when you are doing some smaller operations as well in your property then it is better choice.

Constructor: We can leverage the expression with the constructors as well. Let’s see

// Earlier
public Person(string name)
{
    this.Name = name;
}

// With C# 7.0
public Person(string name) => this.Name = name; 

As mentioned earlier that statement block can’t be used here. So say if I have multiple parameters to pass so I can use another C# 7.0 features: ValueTuple and Destructors.

public Person(string firstName, string lastName) => (FirstName, LastName) = (firstName, lastName);

I wrote some time back on ValueTuples and Deconstructors, you can take a look.

Finalizers: We can use expressions in finalizers as well. Let’s see

// Earlier
~Person()
{
    Console.WriteLine("Person's destructor");
}

// Using Expressions
~Person() => Console.WriteLine("Person's destructor");

There are many new features that got intrudocuced in C# 6.0 and C# 7.X (7.0, 7.1, 7.2) if these are used together, can provide lot of value. The whole idea is write cleaner, concise and more performant code so that the focus is more on business logic.

Hope you are enjoying the enhancements.

Cheers
Brij

Advertisement

Span: A new upcoming feature of C#

With the ground-up changes in ASP.NET with ASP.NET Core which is still going on, it appears that now it is turn of C# language and the run-time. I am sure the ground work must have been going on from last couple of years as these changes required massive ground up changes but I am hoping there are lot more changes will take place in future. After using the power of Span<T> and Memory<T> in ASP.NET Core 2.1, which is claimed to be 70-80% faster than ASP.NET Core 1.X, it is planned to release for all of us. In this post, we will be discussing the new type Span<T>. Before jumping directly into Span<T>, let’s have a quick overview current types.

Every object in C# can be categorized in two type: ValueType and Reference Type. We know Value Type instances gets created on stack and only available in the current scope while reference gets created on managed heap which is taken care by Garbage Collector (GC). Garbage collection is expensive process so if we can minimize the reference type object creation and use more Value Type objects then it could be a huge performance benefit. I am not saying that GC is not properly optimized or similar but no GC is always better that any performance optimized GC.  Let’s understand how Span can help in few scenarios.

Note – Currently this feature is available in prerelease state so some changes in final release are expected. To use this this feature, we need we need Visual Studio 2017 15.5+ version and need to install nuget package – System.Memory (Check the include prerelease checkbox while searching it). You can have a look here if getting an error.

What is Span<T>

Span<T> is a ValueType which allows us write low level code in safe and efficient way without any GC overhead. It’s as efficient as working with unmanaged pointers with the benefits of C#. Span<T> represents a contiguous region of arbitrary memory which could be unmanaged memory, memory allocated on stack and arrays or strings.

Let’s understand it with the help of a string.

Here we can see that when we use Substring method on a string, a new copy gets created on the heap. But, we may not want a new copy as we just read that particular part and even sometimes we may need to update the original string itself. Let’s see how does Span<T> work here

So here we can see that we got a ReadOnlySpan from the string and then used Slice (similar to Substring) method of span to get a specific part of the string but here both the variables refer to same memory location. As span is a struct, lastName doesn’t cost any GC overhead. The two parameters of the Slice method are, starting index and length of the sliced part. Let’s see the complete example

Span<Char> name = "Brij Mishra".ToCharArray().AsSpan();

Span<char> lastName = name.Slice(5,4);

lastName[3] = 'k';

Console.WriteLine(lastName.ToString()); // Prints -> Miskra
Console.WriteLine(name.ToString()); // Prints -> Brij Miskra

lastName[5] = 'k'; // Throws Exception -> System.IndexOutOfRangeException'

Here we can see that change in one character using lastName reflects in both the variables. In the last line, when we try to access the fifth character via lastName, it throws IndexOutofRangeException even we know that we have character at this location. But since lastName was created with only four characters, we cannot access it.

Span vs ReadOnlySpan

As the name suggests Span<T> allows us update the values but many a times, we use the sub-string only for readonly purposes. Say we have a method where we need to pass the part of the string which is just needed for reading purposes, it is safer to pass ReadOnlySpan to save from any accidental update because it will affect all the places inside the program. The current version of the package, returns the ReadOnlySpan while getting the span out of string. So if you are sure that we need the span for read only purposes then we should use ReadOnlySpan. Trying to make any changes in ReadOnlySpan will be an compile time error.

Usages

If you are working with payloads where you create and manipulate strings a lot, it can be quite useful. Similarly, parsing needs usage Substring where it can be quite useful. Other usages are not so common like working with buffers and doing multiple transformations like encoding/decoding, parsing, escaping etc. Working with network buffers can be other quite useful scenario.

Limitations

Span<T> is designed to  stay in the stack onlu which is a limiting factor as well. Few key limitations are

  • We can’t box/unbox because it can’t stay on the heap
  • We can’t have it as fields in classes or even in non-ref structs
  • Cannot be used in lambda method because it might turn into field.
  • Due to stack only field, cannot be use in async methods or iterators

Even having quite many limitations, it can be really helpful where you have big structs, file I/O , Network I/O, string manipulations, working with buffers, synchronous methods.

Hope you have enjoyed the post.

Cheers
Brij

Ref and Out improvements in C# 7.0

If you have been observing last few releases of C#, the key focus of C# language team is to improve the developer productivity by reducing the repetitive/common code and performance of the application. First one, helps a lot in writing cleaner and concise code so it mainly contains logic instead of number of lines for null check etc.

ref and out keywords are available with C# since long and very useful in many scenarios. These were serving the purpose quite beautifully but there were few improvements in C# 7.0 which makes it more attractive. In this post, I am not going to discuss the basics of these keywords detail but mainly focus on the improvements in C# 7.0.

Ref keyword – This keyword is used to pass the parameter by reference (even if it is value type) to a method. When we pass the parameter by reference, any change that takes place in the called method also reflects in calling method. ref keyword should be used by in calling method while passing the parameter and in the called method as well. Also unassigned variable cannot be passed as well. Lets see a quick example

static void Main(string[] args)
{
    Point p;
    p.x = 10;
    p.y = 20;

    UpdateCoordinates(ref p);

    Console.WriteLine($"Point coordinates x : {p.x}, y : {p.y}"); // Output: Point coordinates x : 20, y : 40

    Console.ReadKey();
}

static void UpdateCoordinates(ref Point p)
{
    p.x = 20;
    p.y = 40;
}

public struct Point
{
    public int x, y;
}

Here Point is a value type and it is passed using ref keyword. Here the variable gets updated in the called method and it shows 20 and 40 in output.

Note: ref keyword can be used with reference types as well. You can refer one of my previous posts for details here 

C# 7.0 Enhancements :

As in the example above, the values are passed by reference in the method but what about returning the values by reference. For this, there were two enhancements introduced

1- Ref Returns : For this, we need to add ref keyword after return statement in a method and before the return type in the method signature. This feature can be used only in Class (not structs). Let see the Point class as

public class Point
{
    private int x, y;

    public Point(int a, int b)
    {
        this.x = a;
        this.y = b;
    }
    public ref int GetX()
    {
        return ref this.x;
    }

    public ref int GetY()
    {
        return ref this.y;
    }
      
    public void Display()
    {
        Console.WriteLine($"Point coordinates x : {x}, y : {y}");
    }
}

Here I added two methods GetX and GetY which returns x and y by reference. ref keyword also got added with method signature as well.

2- Ref Locals: To store a reference variable (ref), returned by a method, the local variable should also be added with ref keyword before the type and adding the ref keyword before the method call. Now the local variable contains the value by reference and has the ability to change the value of variable which will reflect in the original variable as well. We can call the method without using the ref keyword which will behave as normal method call and the returned value will be a copy of the value.

static void Main(string[] args)
{
    Point p = new Point(10, 20);

    ref int i = ref p.GetX();
    i = 50;

    p.Display(); // Output: Point coordinates x : 50, y : 20

    int j = p.GetY();
    j = 100;

    p.Display(); // Output: Point coordinates x : 50, y : 20

    Console.ReadKey();
}

Initially the values of x and y are 10 and 20. We got the variable x by refernce and updated it to 50 using variable i which is reflected in output. We also received the value of y without using ref which creates a copy of the variable and updating it doesn’t affect the instance p.

It is a really nice feature in scenarios where the values are required to be updated at different places. This also can be when we have a collection of values and few of the items can be updated by the caller method based on the need.

Enhancements in Out parameter: There is a small enhancements in out parameter usage. Earlier out parameter is used as

static void Main(string[] args)
{
    int age;
    string name = GetUserDetails(out age);
    Console.WriteLine($"name : {name}, age : {age}");

    Console.ReadKey();
}

public static string GetUserDetails(out int age)
{
    age = 32;
    return "Brij";
}

Now after enhancement, we dont need to declare the variable first, instead we can direcly declare in the paarmeter as well as

static void Main(string[] args)
{
    //int age;
    string name = GetUserDetails(out int age);
    Console.WriteLine($"name : {name}, age : {age}");

    Console.ReadKey();
}

Although this is a small enhancement but makes more sense.

Hope you enjoyed the post and will be able leverage these enhancements in your day to day coding.

Cheers,
Brij

Error: CS0619 Span is obsolete

Recently I was exploring various new features of C# 7.x and recently I thought of looking into one cool feature Span but faced hard time to start. So to start with it, one need to install the nuget package System.Memory as

Make sure, you have Include Prerelease check box selected. After that we need to include System.Memory namespace. Once I wrote my first variable as

Upon building the project, I got the following error

I thought something as new as span, how come this be obsolete. I spent some time googling it with no specific result.
I looked my Visual Studio version which Visual Studio Enterprise 2017 v 15.4.2. I thought to update the same as there were few minor releases after that. After updating it to the latest available v15.6.2, I tried again and this time no error.

Initial error was not intuitive enough and updating Visual Studio, i consider last thing unless it is mentioned somewhere.

If you facing similar issue, this may be helpful to you as well.

Thanks
Brij

Read-Only Structs: C# 7.2

C# supports two basic types : Value Type and Reference Type. The main difference between them where they get created: Value Types gets created in stack while Reference type in Heap. Other key difference, for ValueType whenever a parameter is passed as an argument, a copy gets created and passed while for reference types, refernce of the same onstance gets passed. There is another type called – Nullable Type but actually it’s a wrapper over value type. I wrote a post on it, you can have a look here.

All the Value Types internally inherits System.ValueType. Struct is also a ValueType which inherits same.

It’s a good idea to make struct immutable, it means once it is initalized, it cannot be modified. System.DateTime is an immutable Value Type. It provides many static methods but it always returns a new instance.

To make a struct immutable, the simple way to make all the members readonly and initializ these values via parameterized constructor. It’s members should be exposed via getter fields.

Let’s see an example

public struct Person
{
    public string FirstName { get; }

    public string LastName { get; }

    public int Age { get; }

    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }
}

Above struct is immutable as there is no way to modify the initialized variable.

Read-Only structs:

Prior to C# 7.2, to create an Immutable value type, we had to write the struct in a way so that it doesn’t allow an update as in above example. If few fields are left without marking readonly/const unknowingly then it wont work as expected. C# 7.2 allows us to add readonly modifier before struct which makes sure thatg all the members are read only. If any member doesn’t, it will throw an error. Above struct can be marked as read only as

public readonly struct Person
{
    public string FirstName { get; }

    public string LastName { get; }

    public int Age { get; }

    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }

}

One important thing, the parameterized constructor should be used to create the instance always else in case of using parameterless constructor use, the member would be set to default value which cannot be ever changed and we probably won’t want this. We cannot make parameter less private for struct in C# and even if there is a way we can bypass that. We can have some validate method which should be fired before using that struct’s memebers. I wont discuss this in details here.

Read-only struct provides framework support to write readonly struct and help us to avoid any unintended modification. In my previous post, I discussed about In modifier, it also can be used while passing any immutable object. These changes like ref, out, in etc in .NET framework got developed to make low level programming simpler and faster. Few more changes, we will be discussing in coming posts.

Note: If you are not sure how to use X# 7.2 (7.x) in your project, you may have a look on one of my previos post here.

Hope you enjoyed the post.

Cheers
Brij

Using In Parameter Modifier : C# 7.2

Changes are the only constant thing in the world and that got little faster with C# new releases as we have minor now releases (also referred as point releases) with significant enhancements. New features are getting added and existing features are getting enhanced. In one my earlier posts, I discussed about Ref and Out improvements that took places in C# 7.0. You can go through the link below.

Ref and Out improvements in C# 7.0

Let’s have a quick look on it

Here we can see that if we want to pass the argument by ref then reference of the instance (value type or reference type) is passed and any change the in the argument in the called method reflects in the calling method as well.

Note – If you are curious about the using the ref keyword with reference type object, you can have a look to one of my previous posts by clicking here.

Out parameters, are also like pass by reference except it enforces a rule that calling method pass the variable without initializing while called method must initialize.

Say you have a big struct or any other value type, that you have to pass as an argument. Everytime you will call the method, a new copy will be created and passed to the method. If this has to be done multiple times then it can be a major performance issue.

Also, out keyword  forces to the called method to initialize the variable but we dont have opposite option. And ref keyword allows to pass the paramter via reference and here caller and called method both can modify the variable.

C# 7.2 introduced another keyword In which provides the ability to pass the argument as readonly. It fails at compile time if there is any code which tries to modify in the called method. The variable must be initialized before passing as a parameter.

Lets see an example

There are few restrictions.

  1. In, Out and Ref keywords cannot be used in async methods.
  2. Cannot be used in iterator methods (which has yield statements)
  3. Marking the arguments of main method as In, makes it invalid as entry method.

To summarize, In keyword can be really useful when you are passing a big value type object to method which is called multiple times because instead of creating a new copy in each call, it will be passed by reference.

Cheers,
Brij

How to use C# 7.2 (7.x – minor releases) in your Project

C# 7.0 and other minor releases (7.x) are loaded with many awesome features and I’ve been all those nice features recently. You can have a look here. I have seen many people facing issues with using these features. So in this quick post, I will discuss how you can leverage C# 7.x features.

Using Visual Studio 2017

To use C# 7.x features, Microsoft recommends to upgrade the IDE to Visual Studio 2017. To use C# latest minor releases C# 7.X (currently C# 7.2), this is not enough, we need to follow the below steps

  1. Right click on the project => Select Properties
  2. Select Build tab from the left pane.
  3. Go down and select Advanced button
  4. Select the Language version as

Here we can see tha the default selection is C# latest major version (default) which means 7.0. We also have the option to select specific versions like 7.0/7.1 but for 7.2, we need to select C# latest minor version (latest).

Using Visual Studio 2015

As mentioned above that Microsoft recommends to use Visual Studio 2017 for C# 7.x features but as these features are implemented by compiler so as long as your build is pointing to correct version of CSC, you can build the new features. However, Visual Studio 2015 may not like it as it doesn’t understand the new features and you may not get intellisense or any other IDE support.

To use C# 7.X in Visual Studio 2015, install the following nuget package

Microsoft.Net.Compilers

Once, you install this package, you should be able to use the latest language feature in VS 2015. However you might red   squiggly in the editor as

Here we can see that even the VS2015 editor is complaining but it is getting built.

Using System.ValueTuple

ValueTuple is not available by default as part of C# 7.0, we need to install following nuget package

System.ValueTuple

Hope you like the post and able to use the C# latest features.

Cheers,
Brij

.NET Datetime vs SQL Datetime : Comparison, Issues and Workarounds

Hello All,

Recently, in an application where we were saving the .NET DateTime value in SQL database, we had to compare this DateTime later in the .NET application. We realized that even the same DateTime stamp was not equating once it got fetched from database. I got Once we investigated further we found that the time stamp that we were sending to save in database, was not saving with the complete value and there were some more issues. It looks common requirement where you saving a value in database and later comparing it to add some business logic.  So I am sharing here my findings.

# 1

SQL DateTime type only stores time till milliseconds (3 digits) while in .NET it is stored till ticks. One millisecond is equivalent to 10,000 ticks. It means if you construct the .NET DateTime object from the DateTime of database, then it will never match because it will have all zero after the milliseconds. Lets see an example.
Here I am showing the same .NET DateTime value at application, in database table and again .NET DateTime read from the DB.

.NET DateTime

{6/19/2017 9:24:14 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 21
      Kind: Local
      Millisecond: 777
      Minute: 24
      Month: 6
      Second: 14
      Ticks: 636335042547778146
      TimeOfDay: {21:24:14.7778146}
      Year: 2017

Let’s see how it is saved in database.

SQL DateTime

In database table it looks like as


When we fetch from database and convert it into it returns the following object
{6/19/2017 9:24:14 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 21
      Kind: Unspecified
      Millisecond: 777
      Minute: 24
      Month: 6
      Second: 14
      Ticks: 636335042547770000
      TimeOfDay: {21:24:14.7770000}
      Year: 2017

Here we see the TimeOfDay component in both the object then we find that while in first object we have 7778146 while in second 7770000, it means last 4 digits are chopped off and reset to 0.
So is it safe if we compare till milliseconds only (say by using ToString(“MM/dd/yyyy hh:mm:ss.fff”))?
NO
There are some more mystery to it. Let’s see in second point

# 2

Here, I saved a new record in the database and the .net DateTime as
{6/19/2017 11:49:55 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 23
      Kind: Local
      Millisecond: 731
      Minute: 49
      Month: 6
      Second: 55
      Ticks: 636335129957315136
      TimeOfDay: {23:49:55.7315136}
      Year: 2017

and when we see the record in the table, we see

Oh.. here we see the 730 millisecond while in .NET object it was 731. Let’s fetch the same and check the .net object as

{6/19/2017 11:49:55 PM}
      Date: {6/19/2017 12:00:00 AM}
      Day: 19
      DayOfWeek: Monday
      DayOfYear: 170
      Hour: 23
      Kind: Unspecified
      Millisecond: 730
      Minute: 49
      Month: 6
      Second: 55
      Ticks: 636335129957300000
      TimeOfDay: {23:49:55.7300000}
      Year: 2017

Here again we see 730 millisecond. It means we are losing one millisecond. It also suggests that comparing the two values till milliseconds would also not work. But why this is happening. Let’s dig it more.

Actually SQL DateTime stores till 1/3 millisecond approximately so the last digit of millisecond would always be

**0
**3
**7
**0

and SQL rounds of the milliseconds passed to it so if you pass
001 turns to 000
002 turns to 003
004 turns to 004
005 turns to 007

009 turns to 010

So can we just chop off milliseconds and compare the DateTime?
NO

It may work most of the time. But there are few chances to fail. Say we have a time as 09.00.00.999 then it will turn to 09.00.01.000 so here second got increased by 1. Even minute/hour can be changed if similar situation occur. So here we just have the option to round off the time based on the above logic and then compare.

Do we have any other option?
Yes

DateTime2

To overcome this, there is a new SQL data type datetime2 was introduced in SQL server 2008 which got the ability to save the millisecond till 7th precision. It is like an extension of DateTime which saves the time more accurately. Lets have a look on that

So we see here that the time is saved as 2017-06-19 23:49:55.7353342 while the same was saved in DateTime (type) as 2017-06-19 23:49:55.737 (rounded off). If we now fetch the same and assign the .NET DateTime object we get the exact date time and equality works as expected.

Note – There is one more significant update in datetime2. In DateTime if we want to same a default minimum DateTime then it was 1753 but in DateTime it could be 0001.

Conclusion

In this post, we discussed the behavior of SQL DateTime object, its issues and possible workarounds. Then we saw that the how the issues got resolved in datetime2 which was introduced in SQL server 2008. Obviously, it takes more space in database as it saves the time more granular level. I have rarely seen that DateTime values are stored in datetime2 format, mostly in DateTime at least in legacy application. And many of us don’t know the exact difference or may face the issues that we discussed. If we are working on some legacy application then we may not able to change the SQL data type, in that scenario, putting the round off logic could work.

Hope you have enjoyed the post. Do share your valuable feedback.

Happy Coding,
Brij

Singleton vs Static class : Key Differences and Usages

The debate about Singleton vs Static is quite old and it is still continuing and there are lots of confusion around this as well. In this post, I am trying to explain these two concepts, key differences and its usages.In this post I will not focus on the basics of Static and Singleton and how to write that. If you are new to these keywords, I will advise you to learn about these first to get more benefited.

So first we are going to understand the characteristics of each . Lets start with static class

Static Class :

  1. Static classes cannot be instantiated so it restricts us in many ways like it cannot implement Interfaces, inherit any class etc.
  2. Any other scenarios where this keyword is required, it cannot be used like indexer etc. Also it cannot be used as method parameter, local variable etc for the same reason.
  3. Static classes can have only static members – constructor, fields, methods, properties, events.
  4. One cannot control when static constructors are called. It’s always earlier than first access of the class. So no parameters can be passed as well.

Internally when compiler compiles static class, it marks it as a abstract and sealed. So that no instance can be created and cannot be extended as well. Now let’s talk about Singleton

Singleton Class :

  1. As name suggests it allows to have only one instance of a class.
  2. The constructor of this class are marked as private so that accidentally one cannot create multiple instances and provides a static function/property which first create one instance and returns the same each time.
  3. As singleton is a normal class, it allows us to leverage all that features of object oriented programming concepts.

Memory Management :

There is much confusion around memory management of static class and Singleton class. In simple words, any class whether it is itself static or any member if marked as static then it would not be collected by Garbage Collector.

Static variables/classes are not stored in normal Heap and there is a separate space in memory to store static resources which holds the static classes and variables.This space is beyond the scope of GC and memory get release only when corresponding process/AppDomain unloads.

Because singleton holds a static reference which cannot be collected by GC so the instance cannot be collected and both (Static and Singleton) gets destroyed with the AppDomain/Process.

Some Key common characteristics :

  • As both of the static and singleton instances are have just one copy in memory throughout the whole application, both used for holding global state in an application.
  • Both are initialized lazily, it means for static classes it is initialized only when accessed first time and for Singleton, it gets created only when it is accessed first time.

The Differences

  1. Very first difference is that Static is a language feature and Singleton is a architectural pattern so both belongs to difference arena altogether.
  2. Now a days everybody is behind using Dependency Injection and Static does not fit there because it is interface driven.
  3. Unit Testing is another topic where you can find some way to create a mock for singleton instances but testing static is a nightmare.
  4. Being singleton is a just another class, it enable you to use Object oriented concepts.

Singleton approach is much more flexible as we can see that from the differences itself. We can use interface with it and implement it in a class and use in our application. If some requirement changes and later we require to change the logic then we can just remove the older implementation and replace with new one without hiccups as long as the interface is same.. Also testing is another key benefit.

Static classes is mainly recommended for having grouping of a bunch of utility methods that can be called independently but again testing could be a problem and benefits of OOP is gone. So most of the time static should be avoided.

Having said that using global variable (like static class or singleton) makes a strong coupling between the global data and all the places where it is used.

Cheers,
Brij

 

[Video] Learn Garbage Collector (Part -2) : How Garbage Collector runs

Hello All,

This is second part of the series on Garbage Collector. In my last post, I shared first part of the series. In that video, I talked about the basics of Object creation and talked about it’s life cycle. It is very important for understanding the whole Garbage Collection topic. You can find the link of last post below

[Video] Learn Garbage Collector (Part -1) : Object Creation and it’s life cycle

In today’s video, I have talked about when the Garbage Collector triggers and discussed about it’s processing.

Cheers,
Brij