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.
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
Ensure that only one instance of a class is created.
Provide a global point of access to the object.
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.
Related
I was unclear in an earlier question I ask so I will try to be more explicit.
Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?
Here is how I would like to use it:
static class MyStatic : IInterface
{
static void Do(){}
}
static class MyStatic2 : IInterface
{
static void Do(){}
}
class StaticMap
{
static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
{
{Type.1, MyStatic}
{Type.2, MyStatic2}
};
}
// Client Code
class ClientCode
{
void Start()
{
StaticMap.dictionary[Type.1].Do();
}
}
There are some fundamental reasons why you can't do that directly:
Static method calls are bound at compile-time
Static calls are not inherited - they are tied to the class that defines them
There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same
Since your signature is the same for every static method, you could store a Action in the dictionary instead:
static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
{Type.1, MyStatic.Do}
{Type.2, MyStatic2.Do}
};
then you can call the Action directly:
void Start()
{
StaticMap.dictionary[Type.1]();
}
It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.
If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.
However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.
If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.
One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:
container.Register(Component.For<ISomeInterface,SomeClass>));
Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.
Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.
Instead of having the entire class as static, create a Singleton instance.
public class Foo
{
public static Foo _Foo;
public Foo()
{
_Foo = this;
}
}
Then you may add it to your list, and also inherit from Interfaces, etc.
A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].
I have created folders in my project named Classes, Forms, and Models.
Let's say my project is named ABC, so the folder hierarchy is:
ABC
Classes
Forms
Models
In \Models\, I have a class named ApplicationModel.cs, which contains a public method named GetApplications().
However, when I call that method from elsewhere in the same ABC project, I get, "The name 'GetApplications' does not exist in the current context"
I've added:
using ABC.Models;
to the calling class, but it makes no difference. I right-clicked GetApplications() to hopefully see "Resolve" there, but no go.
What must I do to access my own public method?
It would be helpful to see the definition of GetApplications() and the code that's attempting to call it, but I assume it's either a static or an instance method of the ApplicationModel class. In either case, you may have made your code aware of the namespace of the ApplicationModel class with the using statement, but the method must either be called on the class or an instance of the class, like so:
If GetApplications is a static method,
var applications = ApplicationModel.GetApplications();
If it's an instance method:
var appModel = new ApplicationModel(); // or, retrieve the instance from elsewhere...
var applications = appModel.GetApplications();
One way or another, you must refer to the class containing GetApplications in order to call it. If this doesn't help you solve the problem, please edit your question to contain the definition of the method, and the calling code.
Sounds like you're using a static function. Did you forget the static keyword?
A static function "runs" from a class, not an object:
public static string[] GetApplications()
It is hard to give definitive advice without some code on how you are trying to call that method. I can think of two possible ways:
either you are trying to call the method via the ApplicationModel class(ApplicationModel.GetApplications()), in which case you need to declare the method static
or you need to call the method on an object, but you are using the type -- in this case declare/create an object of type ApplicationModel and call the method on that object; (e.g. ApplicationModel model = new ApplicationModel(); model.GetApplications();)
Looks like the class is not marked as public.
You class should be
namespace ABC
{
namespace Models
{
public class ApplicationModel //class needs to be public is accessed outside the namespace
{
}
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
i am not able to understabnd the difference b/w static class and singleton class.
in single ton class we make sure we cretae only one object and no more objects are created.
in a the static class also there is no need to create an object we can call the properties and methods directly using the static class name.
here both looks same so whats teh use of using creating single ton class.
any help on this would be great.
In Static class, there is no object. You directly call methods on the static class.
In Singleton, there is an object however, there can only be one instance of it.
Singleton is useful in conditional creation a resources intensive object. For ex, your application might need a connection to remote database. You might want to make it as singleton to limit the number of connections and also to ensure that its only created when required.
Static class and methods are more like utility functions which can be called whenever required.
The difference, obviously, is that on the one hand, you're working in a static context, and on the other, you're dealing with a normal object instance. I'd say the primary consequence of this is that because static members aren't inherited, a static class can't benefit from inheritance or polymorphism, where a singleton can. By working in a static context, you're losing a lot of the object-orientedness of Java.
With a Singleton, we are assured that only one instance of a class (object) is created. This is highly useful when the object is expensive to create, and there's only ever a need for one.
A static class on the other hand, can have no instances of the class created. This is appropriate when methods don't below to a given object and, instead, act on existing objects.
First let's see an example to explain static/instance (code is in as3 but same principle in any languages)
class Blob {
private var i:int=0;
public function Blob() {
i++;
trace("I value : " + i);
}
}
new Blob();
new Blob();
------
output
I 1
I 1
you have 2 instances of your Blob class and i var is create each time.
class StaticBlob {
private static var i:int =0;
public function StaticBlob() {
i++;
trace("I value : " + i);
}
}
new StaticBlob();
new StaticBlob();
--------
output
I 1
I 2
you have 2 instances of your StaticBlob class too but i var is only create once and "keep in memory" for all the instance
Now it's more easy to understand Singleton.
Singleton garantees you to have ONLY ONE INSTANCE of a class (because it uses a static property to keep the reference of your instance and return it).
So it can be use to instanciate one time an object (for example if your object consume too much resource to create)
A singleton class is very different from a static class in that a singleton class can contain static and non static members/properties/methods.
So a singleton object can persist information/state like a normal non static object. Most importantly a singleton is designed to be Thread safe, that is it has a sync root object (generally) that can be used to block threads that are trying to do the same thing.
A static class can only contain static members/properties/members because of this it is impossible to maintain thread safety you cannot lock a static object.
Never seen this done in asp.net, but never the less, can I define functions without being part of the class?
What I would like to have is a utility library. Currently I have Utils class and every time I need to use it for things like populating drop down lists i have to create and init the Utils() object...any way around that hassle aside from declaring the class static which I would rather not do as I access session in it?
I am using c#, not VB.
Thanks
There's no way to have methods outside of classes.
The typical solution in your case is to create a Utility class full of static methods...that way you don't have to worry about creating an instance of the class to utilize its methods.
And like Joel mentioned...you can still access the session from a static method.
You can always use Extension Methods.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
You can then add the methods on to the existing objects.
You could also create a base class which all your pages inherit from and have that contain the methods you need. It's still part of a class, but you don't need to instantiate a new one, or use static methods.
You can still access Session variables in a static class. One way might be like this:
public static class Utils
{
private static HttpSessionState Session
{
get { return HttpContext.Current.Session; }
}
public static string DoThing(string input)
{
// here you can access session variables like you're used to:
Session["foo"] = input;
}
}
You could have all you pages derive from a BasePage class and put all of your util methods (or wrappers to them) into the base page class
If the class has state then leave it alone. Alternatively, take your state as parameters and then make it static.
You can access the Session variables using HttpContext.Current.Session[], and you can do this from any class (In fact, in many applications I have that use Session variables, I encapsulate all of my session variables in their own class).
Having said that, there is no way to have a method outside of a class, and there really isn't a [good] reason to do so.