I have created a function in a class. and i want to call it throughout my project. but i don't want to create the object of that class in every page. is there any global declaration for that class so that we can call in every page ? Inheritance is not possible in code behind file of aspx page .cs file.
Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
Like static data members, you may access a static member function f() of a class A without using an object of class A .
We can also make class methods that can be called without having an instance. The method is then similar to a plain Python function, except that it is contained inside a class and the method name must be prefixed by the classname. Such methods are known as static methods.
You just need to make it a static method: public class Foo { public static void Bar() { ... } } Then from anywhere: Foo.
You need to create a Static
Method in your class so that you can call the function without creating an object of that class as shown in following snippet:
public class myclass
{
public static returntype methodname()
{
//your code
}
}
to call the function just use
//ClassName.MethodName();
myclass.methodname();
you can have look at MSDN: Static Members
Suggestion
One more resolution to your problem is to make use of SINGLETON DESIGN PATTERN
Intent
You just need to make it a static method:
public class Foo
{
public static void Bar()
{
...
}
}
Then from anywhere:
Foo.Bar();
Note that because you're not calling the method on an instance of the type, there won't be any instance-specific state - you'll have access to any static variables, but not any instance variables.
If you need instance-specific state, you'll need to have an instance - and the best way of getting hold of an appropriate instance will really depend on what you're trying to achieve. If you could give us more information about the class and the method, we may be able to help you more.
Admittedly from what I remember, dependency injection in ASP.NET (pre-MVC) is a bit of a pain, but you may well want to look into that - if the method mutates any static state, you'll end up with something which is hard to test and hard to reason about in terms of threading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With