Singleton instance vs Static in terms of Memory Management

Emil Alipiev 271 Reputation points
2020-12-03T16:26:02.953+00:00

Using static viewmodels or properties may cause memory leaks as we know if not handled properly, GC will not dispose those viewmodels and views. Is it the same issue when using Singleton instance with DI? i need to access ViewModel function within the Android native class. What will be the best solution for that without doing "new" instance?
I do currently

Xamarin.Forms.DependencyService.Get<IViewModelModel>(Xamarin.Forms.DependencyFetchTarget.GlobalInstance);

does GlobalInstance reuse the existing initialized instance?

Because instance is already initialiized and native class should execute the function within this class?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2020-12-04T11:59:29.677+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    There is no best, only more appropriate. We should first know the difference between singleton mode and static mode.We can choose what works for us based on our needs.

    Static Class:

    You cannot create the instance of static class.

    Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

    We cannot pass the static class to method.

    We cannot inherit Static class to another Static class in C#.

    A class having all static methods.

    Better performance (static methods are bonded on compile time)

    Singleton:

    You can create one instance of the object and reuse it.

    Singleton instance is created for the first time when the user requested.

    Singleton class can have constructor.

    You can create the object of singleton class and pass it to method.

    Singleton class does not say any restriction of Inheritance.

    We can dispose the objects of a singleton class but not of static class.

    Methods can be overridden.

    Can be lazy loaded when need (static classes are always loaded).

    We can implement interface(static class can not implement interface).

    And there are some good threads about this, you can check it here:

    Difference between static class and singleton pattern?

    and

    Singleton Pattern Versus Static Class

    Best Regards!

    Jessie Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments