Search Unity

how does the "<someType>" thing work?

Discussion in 'Scripting' started by craig4android, Oct 8, 2019.

  1. craig4android

    craig4android

    Joined:
    May 8, 2019
    Posts:
    124
    I want to create a method, which returns the type defined in those brackets like so:

    Code (CSharp):
    1. public function T returnSomething<T>(){
    2.  
    3. return new T();
    4. }
    and T can be any type, if the Type isn't support then it will return null.
    Just like the MonoBehaviour.getComponent<>() Method.

    How to do this?

    Edit:
    hmm seems to work already, kind of...
     
    Last edited: Oct 8, 2019
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,334
    If the components on a MonoBehaviour was just an list of Components, the GetComponent<T> method would look like this:

    Code (csharp):
    1. private List<Component> components;
    2.  
    3. public T GetComponent<T>() {
    4.     foreach(var component in components) {
    5.         if (component is T) {
    6.             return (T) component;
    7.         }
    8.     }
    9.     return null;
    10. }
     
  3. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    If you remove the "function" word, it is mostly correct. Your type is T, since that's your return type. You have nothing to return, so as a very simple and useless example, let's give it the thing it's supposed to return as parameter. Then it looks like this:
    Code (CSharp):
    1. public T Something<T>(T input){
    2.     return input;
    3. }
    Here we give the method something of some type T, and then return something of the same type (in this case the same object we got as input). I dont think you can create a "new T()" tho, as some constructors expect parameters. If that's possible, then it's not safe, so you'd need to restrict the allowed types somehow and throw an exception if it's something else.

    Generally speaking, the keyword you are looking for is "generics":
    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Specifically, you'd need to add a "where" statement onto the function definition to ensure that it has the desired constructor:
    Code (csharp):
    1. public T Something<T>() where T : new()
    2. {
    3. return new T();
    4. }
    There are a ton of kinds of restrictions you can put into a "where" statement to ensure that the supplied class fits any needs you have to.
     
    Antistone, Yoreki and lordofduct like this.