class CPU
{
string itemName;
public CPU(string itemName)
{
this.itemName = itemName;
}
}
then have dictionary
Dictionary<string, CPU> cpu = new Dictionary<string, CPU>();
how to create get method for dictionary? i mean easy normal way since ive been thinking you can return keys, select keys call another function that accepts keys and then returns some data but its complicated.
TLDR how to return dictionary without making CPU class public?
something like this
public Dictionary<string, CPU> GetCPU()
{
return ...;
}
Return dictionary to who? My understanding is when you declare a class as private you do so within a parent class. Then you’d declare the Dictionary as public in the private class, and it should be accessible as normal from the parent class. But it won’t be accessible outside of the parent class. If you want to access the Dictionary from anywhere, well why not declare the class as public?
yeah it is from another script so outside class “database” (where dictionary is stored), as to reason WHY well I wanted to use get set or custom get set as to keep scope but yeah seems ive overdone it since this is database class that hold lots of data. well guess ill use public class and dictionary and use it as such
In general, if you have an object of a private type, but you want to return it in a public function, you have to return it as a more generic type. For example:
public class A
{
// stuff
}
private class B : A
{
// stuff
}
private B instanceOfB;
public A GetMyB()
{
return instanceOfB;
}
The caller is actually getting an instance of the subtype, but you don’t promise that it’s an instance of the subtype, you just promise it’s an instance of the supertype. Presumably you’ve set up your classes such that everything the caller needs access to is inside the definition of A, and they’ll just ignore the additional stuff inside of B.
Even if you didn’t explicitly create a public base class, it’s usually possible to go more generic. In Unity, a lot of your classes probably inherit from MonoBehaviour, which could also be returned as something like Component or UnityObject. In an extreme case, you can usually return something as System.Object, which all classes ultimately inherit from.
Of course, there’s not very much that the caller can do with a System.Object.