C# - static method or create new Instance when using third party library

what is the use of static class in c#.net with example
when to use static class in c#
when to use static methods c#
c# static variable in method
static class in c# with real time example
advantages of static class in c#
alternative of static variable in c#
how to use non static variable in static method c#

I have a class that only implement a third party library - And I can tell you that is Google Cloud.

I'm wondering while using this kind of libraries, how to use it properly?

Here are my examples show how I use:

New Instance

Declaration

public class MyClass{
        private readonly string _jsonPath= ...;

        public readonly StorageClient Client;

        public MyClass()
        {
            var credential = GoogleCredential.FromFile(_jsonPath);
            Client = StorageClient.Create(credential);
        }

        public string Upload(/*my parameter*/)
        {
            Client.UploadObject(...);
            // etc
        }
}

Usage

var myInstance = new MyClass();

myInstance.Upload(...);

Static Method

Declaration

public class MyClass{
        private static readonly string _jsonPath= ...;

        public static readonly StorageClient Client = StorageClient.Create(GoogleCredential.FromFile(_jsonPath));

        public static string Upload(/*my parameter*/)
        {
            Client.UploadObject(...);
            // etc
        }
}

Usage

MyClass.Upload(...);

Since the methods will be called concurrently very frequently, I would like to know what kind of usage is better and why to avoid problems.

As far as I know, static is not good at sharing the same class members,

but I think to declare the client every time I need to use is redundant.

I would like to know more about this two way's pros and cons.

Any advice will be appreciated.

My English is pretty basic, please don't mind.

Thanks for your reading.

Depending on your MyClass requirements, this is a bit tough to answer. What does MyClass do? Does it require some setup? Building? Does the Upload method depend on instance state?

I generally like to inject my external dependencies, and hide them behind interfaces. That way I create test doubles, and easilly change the dependencies if I want to. I tend to not like using statics unless it is for stateless utility classes, like Maths, string manipulation, extensions and other stateless processing.

For things that require state, I use instances. If I really need shared state, I use a singleton, but I try to avoid them if possible.

In your case I would create a IStorageProvider, implement a GoogleCloudStorageProvider, and put a dependency of IStorageProvider on MyClass.

public class MyClass {
    IStorageProvider Storage;
    public MyClass(IStorageProvider storage)
    {
        Storage = storage;
    }
    public async void Upload(Data data){
        await Storage.Save(data);
    }
}

public interface IStorageProvider{
    void Upload(Data data);
}

public class GoogleCloudStorage:IStorageProvider{
    private Credentials Creds;
    private GoogleCloudClient Client;
    public GoogleCloudStorage(Credentials creds)
    {
        Creds = creds;
        Client = new GoogleCloudClient();
    }

    private void Connect(){
        Client.Connect(Creds);
    }
    public async void Upload(Data data){
        if(!Client.Connected){
            Connect();
        }
        return await Client.Upload(data);
    }
}

I feel that this approach is a bit more flexible.

Working with static class in a dynamically loaded third party assembly, MemberAccessException was unhandled: Cannot create an abstract class. Obviously I can't use CreateInstance method because the static class  C#: Adding Functionality to 3rd Party Libraries With Extension Methods. Ever have one of those third party libraries that you love but it's missing that one feature or one piece of syntactical candy that would make it so much more useful? This, I truly think, is one of the best uses of extension methods.

You can use static class for often use component.but I recommend you should use singleton design pattern for this process.

Don't Use "Static" in C#?, I use static when I am not going to create an instance of a class because the class but there are times when a library class is probably a more natural expression of me of extension methods, which of course have to be in static classes in C#. a member that is using no data from that class, probably it should not be part  The code to call a static method is almost the same as calling an instance-level one. The key difference is that we pass in null as the first parameter to Invoke. That parameter specifies which instance the method should be invoked on.

I would go with your first approach and change your Upload method to be asynchronous so that independent tasks can run concurrently. With your second approach you could have two different threads which are altering the same object in a non thread-safe way.

Do something like this:

public class MyClass{

    private readonly string _jsonPath= ...;
    private readonly StorageClient _storageClient;

    public MyClass()
    {
        var credential = GoogleCredential.FromFile(_jsonPath);
        _storageClient = StorageClient.Create(credential);
    }

    public Task<string> UploadAsync(/*my parameter*/)
    {
        var imageObject = await _storageClient.UploadObjectAsync(...);
        // etc
    }
}

Static Classes and Static Class Members, In other words, you cannot use the new operator to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations,  @tereško: The C# language requires static methods to be part of a static class, if you don't want to have to create an instance of the class to call the method. @quetzalcoatl: It's perfectly legal to pass a delegate (i.e. a different algorithm) to a static method; the extension methods in Linq are all static methods.

How to implement and call a custom extension method, Implement the extension method as a static method with at least the same visibility as In the calling code, add a using directive to specify the namespace that Call the methods as if they were instance methods on the type. Project templates often create a method named Run, but the method name can be any valid C# method name. The trigger attribute specifies the trigger type and binds input data to a method parameter. The example function is triggered by a queue message, and the queue message is passed to the method in the myQueueItem parameter.

Methods, A return type of a method is not part of the signature of the method for Attempting to call a static method through an object instance are calling a static method), add a period, the name of the method, and parentheses. of type int named num; the second, a numeric constant; and the third, an expression. new operator (C# reference) 06/25/2019; 2 minutes to read; In this article. The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint. Constructor invocation. To create a new instance of a type, you typically invoke one of the constructors of that type using

Professional Visual Studio 2005, C# now permits a class to be marked as static, which not only prevents an instance of the class being created, it also prevents any class As such, it cannot contain instance variables or methods. However, this alone is not enough, as quite often you don't have control over how types in third-party libraries are named. ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

Comments
  • Got it! MyClass do only collect and transform data that will be needed by google functions. I have created several class for several google service. So I think it's more like static method but I don't know using google sdk instance as static is proper.
  • I don't know what's the difference between singleton and static method here.
  • c-sharpcorner.com/blogs/… medium.com/@hakantopuz/…
  • oh, I know the difference of both. I mean it looks like no difference between them in my usage. But thanks anyway.
  • That's a good idea. But I would like to know what if the third party library doesn't implement an asynchronous method? Could I use it by single instance safely?
  • @TerryWei You are using ASP.NET MVC which means that the framework will always instantiate a new controller instance for each http request. So it's not thread-safe to call methods from your "MyClass". However, if your library doesn't provide asynchronous methods, you just can wrap those calls in Tasks.