Home > database >  Is it possible in C# to reference an object in another object, when data type is not known at compil
Is it possible in C# to reference an object in another object, when data type is not known at compil

Time:10-28

I'm writing a small game in Unity (C#). I have two classes, e.g. Person and Company. I have a third class "Objects" which represents stuff of any kind.

An instance of the Obejcts class has to contain a variable "owner", either a Person or a Company. During runtime the owner must change between Company and Person data type. I cant just assume that the possessor of the object is the owner, due to game concept.

The following is exemplary code:

public class Person {
    public List<Objects> inventory = new List<Objects>();
    ...
}


public class Company {
    public List<Objects> inventory = new List<Objects>();
    ...
}

public class Objects {
    public Person, Company owner; // just exemplary two possible data types
    ...
}

Im "translating" the code from Python, so this procedure wasn't a problem before but now it is.

In short, i dont want to alter my data in any way, i only want to change the data type of the variable itself (called literal i think) during runtime. Or to "disable" the type checking for this variable.

My "working" solution is to implement two owners variables for Persons and Companies, but its very error prone and i have to write a lot more code to accomplish the same functionality.

Data Type var doesn't work for me because the owner variable has to be public. Data Type object doesn't work either, because i can't call the methods of class Objects.

I've read about reflection and interfaces, but i dont think that thats what i need tbh.

Dynamic would have been possible, but the Data Type must be changed for multiple times, e.g. Person -> Company -> Person.

CodePudding user response:

Either use an interface

public interface IOwner
{
    public List<Objects> inventory { get; }
}

public class Person : IOwner 
{
    public List<Objects> inventory { get; private set; } = new ();

    ...
}

public class Company : IOwner 
{
    public List<Objects> inventory { get; private set; } = new ();

    ...
}

public class Objects 
{
    public IOwner Owner;
}

or common base class

public abstract class Owner
{
    // shared implementations
    public List<Objects> inventory = new();
}

public class Person : Owner 
{
    ...
}

public class Company : Owner 
{
    ...
}

public class Objects 
{
    public Owner Owner;
}

Alternatively you could use the mother of all types object (= System.Object)

public class Objects 
{
    public object Owner;
}

or dynamic

public class Objects 
{
    public dynamic Owner;
}

Depends a bit on whether you really only want to store a reference or actually do something with/through it

  • Related