Calling a function from a class file without creating an object of this class

I created a function in the class. and I want to call it throughout my project. but I do not want to create an object of this class on every page. Is there a global declaration for this class so we can call every page? Inheritance is not possible in the code behind the aspx.cs file.

+8
source share
2 answers

You need to create the Static method in your class so that you can call the function without creating an object of this class, as shown in the following snippet:

 public class myclass { public static returntype methodname() { //your code } } 

to call a function just use

 //ClassName.MethodName(); myclass.methodname(); 

you can see MSDN: Static members

Sentence

Another solution to your problem is to use SINGLETON DESIGN PATTERN

Intention

  • Make sure that only one instance of the class is created.
  • Provide a global access point to the object.

UML diagram

+13
source share

You just need to make it a static method:

 public class Foo { public static void Bar() { ... } } 

Then from anywhere:

 Foo.Bar(); 

Note that due to the fact that you are not calling the method on the type instance, there will be no specific state of the instance - you will have access to any static variables, but not to any instance variables.

If you need a specific instance state, you need to have an instance - and the best way to get the corresponding instance will really depend on what you are trying to achieve. If you can provide us more information about the class and method, we can help you more.

In truth, from what I remember, dependency injection in ASP.NET (pre-MVC) is a bit sick, but you might want to study this - if this method changes any static state, you end up with something that difficult to verify and difficult to reason in terms of thread.

+4
source share

All Articles