Class Reference Shortcut - c#

I currently have two solutions inside my project.
Solution 1 is the GameEngine
Solution 2 is essentially the front end Adventure
In order to access classes from the GameEngine library a Singleton design approach is used, so for me to access my inventory class for example GameEngine.Instance.Inventory is used.
However, this is adding quite a lot of code now, doing GameEngine.Instance each time, is there a way I can invoke a method or return so I can simply refer to Inventory and it will return the GameEngine.Instance.Inventory class instead? Basically a shortcut.
Thanks In advance :)

One way is to set up a property:
public GameEngine.Inventory Inventory
{
get { return GameEngine.Instance.Inventory; }
}
Now you can use Inventory all over the class to refer to your singleton object. However this will work only within a particular class.
Also, as per #Leri's comment, this migth (and might not) affect performance.

Use a static property:
private static GameEngine.Inventory _inventory;
public static GameEngine.Inventory Inventory
{
get {
if (_inventory == null) {
_inventory = GameEngine.Instance.Inventory;
}
return _inventory;
}
}

You can also add a static method so it will be accessible through the entire project
public static ClsInventory GetInventory()
{
return GameEngine.Instance.Inventory;
}

If your singleton instance is never changed, you can safely use a variable for the instance:
var i = GameEngine.Instance;
then use it with:
i.Inventory

I would like to augment the answers.They all respond properly your question and I upvoted all. However, I would recomend instead of using a singleton, try to change your aproach to injection of dependencies to acces "global" instances.
What would happend when you want to acces other (global) object rather than the inventory? You will have to add another property to your GameEngine. Your engine will become a Frankestain with so many properties belongin to game engine internal instances. This violates the single responsablity pattern.
Besides, when you want to unit test your game, you wil have to setup the ENTIRE GameEngine for each test / fixture. IOD also helps you to decouple your code.

Related

Static "interface" of singleton class

The word "interface" here does not refer to the C# keyword. If you know a better name for the method I'll describe in this question, please let me know.
I use a singleton in one of my program.
And while programming it, I just thought it would be great to have all the singleton's methods implemented in static as well, acting as an "interface" of the singleton.
The point would be to write
int ret = MyClass.GetValue();
instead of
int ret = MyClass.singleton.GetValue();
That's what I describe as being an "interface" of a singleton and here is how I would implement it.
public class MyClass : MonoBehaviour
{
private static MyClass singleton = null;
private int theValue = 123;
private int InstanceGetValue();
{
return theValue;
}
public static int GetValue()
{
if (singleton == null)
return default(int);
return singleton.InstanceGetValue();
}
private void OnEnable()
{
if (singleton == null)
singleton = this;
}
private void OnDisable()
{
if (singleton == this)
singleton = null;
}
}
So my question is:
What am I missing that could explain why this is not common practice when using singletons?
It makes every call look much better and it is simple to implement! Why is this not the default way of using singletons?
This is Unity code but you might be able to answer my question even if you don't use Unity. Just so you know, OnEnable is automatically called when this object become active in this scene and OnDisable is called when your object become inactive.
Let's not talk about whether using singletons is a good practice in C# in this topic. A lot of great topic are already answering this question.
What it seems you're doing here is trying to write an adapter to allow for accessing the singleton. If you look at the Wikipedia page on the Singleton pattern you'll note that the implementation details around it specifies two requisites.
ensure that only one instance of the singleton class ever exists
provide global access to that instance
What you're trying to do here is hiding that global access which brings me to believe that you're trying to hide the global access point or just plain want to write less code by excluding the singleton call from the following: MyClass.singleton.GetValue();
I think the main question you'd have to ask yourself here is which of the two your trying to achieve. If you're trying to hide the global access point I'd suggest looking at why you're using a singleton in the first place, but if you're trying to write less code I'd rather question why you're trying to write less code and if you're not using some hard to read coding practices.
EDIT: I understand why you'd only want one instance in the scene, but I'd rather just take full responsibility of managing that lifecycle instead of just trying to leverage the singleton pattern for this.

what is the need of Adapter Design pattern?

In the below adapter design pattern sample code, why a new class is introduced instead of using multiple interface in the client?
interface ITarget
{
List<string> GetProducts();
}
public class VendorAdaptee
{
public List<string> GetListOfProducts()
{
List<string> products = new List<string>();
products.Add("Gaming Consoles");
products.Add("Television");
products.Add("Books");
products.Add("Musical Instruments");
return products;
}
}
class VendorAdapter:ITarget
{
public List<string> GetProducts()
{
VendorAdaptee adaptee = new VendorAdaptee();
return adaptee.GetListOfProducts();
}
}
class ShoppingPortalClient
{
static void Main(string[] args)
{
ITarget adapter = new VendorAdapter();
foreach (string product in adapter.GetProducts())
{
Console.WriteLine(product);
}
Console.ReadLine();
}
}
I have the below queries related to the above code.
What, if ShoppingPortalClient directly inherits VendorAdaptee?
In which scenario we need adapter class?
why instead of simple inheritance a needed class, creating this pattern to access another class method?
Sometimes you have a given API that you can't change (legacy/external-library/etc...) and you want to make your classes be able to work with that API without changing their code.
Lets say you use an API which has an ISomethingToSerialize
public interface ISomethingToSerialize
{
object[] GetItemsToSerialize();
}
That API also has a Serialize function:
public class SerializationServices
{
byte[] Serialize(ISomethingToSerialize objectToSerialize);
}
Now you have a class in your code, and you don't want or not able to change it, let's call it MyUnchangeableClass.
This class doesn't implement ISomethingToSerialize but you want to serialize it using the API so you create AdapterClass which implement ISomethingToSerialize to allow MyUnchangeableClass to use it without implementing it by itself:
public class AdapterClass : ISomethingToSerialize
{
public AdapterClass(MyUnchangeableClass instance)
{
mInstance = instance;
}
MyUnchangeableClass mInstance;
public object[] GetItemsToSerialize()
{
return mInstance.SomeSpecificGetter();
}
}
Now you can use
MyUnchangeableClass instance = ... //Constructor or factory or something...
AdapterClass adapter = new AdapterClass(instance)
SerializationServices.Serialize(adapter);
to serialize an instance of MyUnchangeableClass even though it doesn't meet the requirements of the API by itself.
You've got the idea totally wrong. The VendorAdaptee is the instance of code that produce data, where the ShoppingPortalClient is the one who wants to consume it.
Let me explain what would be the real world situation. You are implementing the shop, and someone else has been implemented a service to give you data about their products(VendorAdaptee). The simple way of doing it is to simply call their methods and use the data, right? But it is their service and they might want to change it later while you don't want to upload your whole solution and release a new version. Therefore, you need an adapter in between to make sure that the data will be send to your real code with the format that you need, and you simply don't care about the address, method name or data format that has been supported by your vendor.
about your questions:
Inheritance is not in any way the case. Conceptually speaking, a shop is not a vendor in any way. considering the code, you have nothing similar in any of those 2, and the behavior is totally different. one is providing data while the other use it.
The main reason you would use an adapter is for legacy code that you don't want to mess with - or a third party that you won't to fit into a certain interface.
There are other reasons, usually depending on how you find easier to develop and if using the adapter design pattern makes sense to you. I don't see it as very useful in other cases though.
First of all I also don't think this is a good example for Adapter pattern. Adapter pattern is much meaningful when you can't directly use one particular kind of class(say A) in your class(say B), instead you implement another class(say C) which can be directly used inside your class (B) and it(C) can directly use the first one(A).
You might ask what will be the examples where B cannot directly use A. There's few.
A's methods don't return the type which is ideally needed by B.
So we don't to mess up with adding the conversion need by B inside B. Instead we give responsibility to C to do it for B.
It might not look natural for B to contain A. etc.
Back to your questions
(1) It is meaningful if you ask,
What, if ShoppingPortalClient directly 'uses' VendorAdaptee?
Just because it is the main class, it has been used as a demo, not to show the structure. And one thing to add, just because you want to call another class's method, don't inherit it unless it is meaningful. In this scenario composition is preferred. For the question why not 'using', just assume it cannot. But you rather ask why cannot. The answer I can give in this example is just assume it is not natural to call Adaptee. That's why I said it is not a good example. :)
(2), (3) I think you can get the answer from the description I have provided so far.

C# in Unity 3D/2D: Am I required to use Classes for every script?

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].

What is the equivalent of a C/C++ global variable?

I am new to C#. Come from the C/C++ environment. My application has a List<Model> which is required all over the place, by different classes. The problem is that a copy will not do because this statement:
dataGrid.ItemsSource = myModelList;
requires the original by address. I tried changing some arguments around and passing that particular variable as ref but as soon as it is assigned with an equal sign, I end up with a copy. Correct?
You could make it a singleton.
However a concrete List needed all over the place would make me have a serious think about my design.
At the very least you should consider writing a class to control access to the list (add, remove, clear etc), and making that "global", otherwise you are going to be in deep in the brown stuff, until it hits the fan.
Create a Public Class and have the content you wish to pass declared static within the class. Then just access it as NameOfClass.NameOfMethod()
public class NameOfClass
{
public static RETURNTYPE NameOfMethod()
{
// Your Code
}
}
You can create a public class for it with a public static List inside it. That one you then can access everywhere.
eg
public class FakeGlobal
{
public static List<Model> MyModelList = new List<Model>();
}
or even make it a property with getter/setter.

Cross class communication without refering the instances C#

I have two classes that are instantiaded and loaded at runtime. I would like to check the resources of one without having to refer the instances as it can get messy if there are a lot of checks and classes.
For example, if I have the two following classes and I want to call one from another.
Class Item
{
private int id;
private int loc;
void Item()
{
// the Class actually has some properties with get set, but thats not the point here.
id = 1;
loc = 2;
}
public bool check()
{
// Check if the several fields are ok for DB submission
// how Can I refer to the other class from here? Do I have to pass the instance as a parameter?
return Locals.Exists(loc); // does not work because its not static!
}
}
Class Locals
{
Hashtable l = new Hastable();
void Locals()
{
// This will actually be loaded from a DB at runtime.
l.add(1, "Local 1");
l.add(2, "Local 2");
}
public bool Exists(int i)
{
return l.ContainsKey(i);
}
}
//Form Code:
main()
{
Item newItem = new Item();
Locals allLocals = new Locals();
newItem.check();
}
Is there a way to do this without having to call
newItem.check(allLocals);
From what I saw, even with delegates, the caller classe need the instance of the other class.
In short, Is there another way to promote cross Instances communication?
Was I confusing enough?
not sure i understand what you mean, but i usually add for similiar cases a static list with all of the objects
Class Locals
{
public static List<Locals> MyLocals = new List<Locals>(); // first thing i add
Hashtable l = new Hastable();
void Locals()
{
// This will actually be loaded from a DB at runtime.
l.add(1, "Local 1");
l.add(2, "Local 2");
MyLocals.Add(this); // second thing i add
}
and then you can get the objects from a static context.
be sure to edit the dispose function as well, otherwise the GC will not work.
It's not entirely clear what you're trying to accomplish here, but one option to fix the problem of passing lots of instances around is to use an IoC framework (Ninject is one example, but there are several available to choose from.) Because instances are injected dynamically as your objects are constructed, this can help to reduce inconvenient glue code. There are other patterns available to allow the classes to find eachother (a Singleton instance or some form of Repository that allows lookup of an instance using some identifying data.) It's also possible to use a Message passing design, which strongly decouples the classes, at the cost of some additional overhead.
It really depends on what you're trying to do. Every design will have its pros and cons.
How can I refer to the other class
from here? Do I have to pass the
instance as a parameter?
Yes, the only way to communicate with an instance is to get a reference to it (or an intermediary). Since Locals isn't a static class, pass an instance to an Item constructor or method parameter.

Categories