1

I have a method in my MVC App that creates a pdf file (takes an object with data to write and path as parameters). I wrote the method in a seperate class and i made it static. In another function on my controler, i call this method like this:

PdfGenerator.GeneratePdfMethod("write this string", "path");

Now if i change this method to non static, i have to instatniate a PdfGenerator object and then call the function on that object:

PdfGenerator p = new PdfGenerator();
p.GeneratePdfMethod("write this string", "path");

Now how can i avoid having to create this object while not making my method static? If it is even possible and advisable?

6
  • 3
    This is the very difference between static and instance methods, try a google search on "static vs instance method". If you want to call it with just one line of code you could write new PdfGenerator().GeneratePdfMethod("write this string", "path"); Commented Mar 27, 2020 at 10:25
  • i know this, but could i somehow make it inherit for another class or instance of some object? Commented Mar 27, 2020 at 10:30
  • 1
    I don't see the reason why you don't want to make this static. Are you only using pdfGenerator on 1 method? Or are you using it in multiple methods on different controllers? Commented Mar 27, 2020 at 10:31
  • I only use it on one method. I just want to know id there is an other way to call it if its not static. This project is from someone else, i am adding just this method, and i see most other functions in this mvc app are not static. Commented Mar 27, 2020 at 10:36
  • i preffer it to be static, but the person i make this for doesnt want static methods in their app for some reason Commented Mar 27, 2020 at 10:37

1 Answer 1

2

Now how can i avoid having to create this object while not making my method static? If it is even possible ...?

No. You'll have to create an instance of the class before you can access any of its members, including the GeneratePdfMethod method.

You can do this on one line though:

new PdfGenerator().GeneratePdfMethod("write this string", "path");

When a member is static, it doesn't belong to a specific instance but rather to the type itself.

On the opposite, a non-static method belongs to a specific instance which means that you need a reference to this particular instance before you can call the method.

If GeneratePdfMethod doesn't access any instance data, it should be static though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.