Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to pass a class type in method arguments?

Discussion in 'Scripting' started by smallstep, Mar 8, 2018.

  1. smallstep

    smallstep

    Joined:
    Jan 25, 2016
    Posts:
    34
    I'm writing a class to implement a generic file saver/loader. Inside a method I need to take as input the instance of a data class (with some specific fields that vary from instance to instance), load a file from binary and pass the info to that referenced object according to its class type.

    How can I pass the type of it's class in the arguments? I need to call the Saver.Load() from a different class somewhere else in my code and use it for many different dataClasses. Is this possible with C#?


    Code (CSharp):
    1. public void Load(object dataObject, string folderPath, string filename, string format, bool encrypt)
    2. {
    3. string path = Path.Combine(Application.persistentDataPath, folderPath);
    4.         path = Path.Combine(path, filename);
    5.         if (File.Exists(path))
    6.         {
    7.                 BinaryFormatter bf = new BinaryFormatter();
    8.                 FileStream file = File.Open(path, FileMode.Open);
    9.                 dataObject = (dataClass)bf.Deserialize(file);  //  << ----I need a parametric dataClass here------
    10.                 file.Close();
    11.             }
    12. }
    13.  
     
  2. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    389
    You may want to look into generics

    A quick example:
    Code (csharp):
    1. public T Load<T>(string folderPath, string filename, string format, bool encrypt)
    2. {
    3.   //sanity checks
    4.   var bf = new BinaryFormatter();
    5.   var file = File.Open(path, FileMode.Open);
    6.   T result = (T)bf.Deserialize(file);
    7.   file.Close();
    8.   return result;
    9. }
    10. //usage:
    11. MyDataClass objToLoad = Load<MyDataClass>(string, string, string, bool);
    12.  
     
    smallstep likes this.
  3. smallstep

    smallstep

    Joined:
    Jan 25, 2016
    Posts:
    34
    Thanks, it works nicely for my purposes!