'Get trait in subclass

I'm sorry if this is poorly worded or if this has been asked before but I couldn't seem to find anything related to this and I'm quite tired.

Alright, so what I'm trying to do is get the value of of my trait in a subclass for situations where I need to reference an instance of a subclass but I don't have the information about what trait it will be using. This is easier for me to explain in code so here's what I'm trying to do.

public class TraitUser<T> 
{
    public void DoThingWithT(T thing) 
    {
        thing.ToString();
    }
}

public class TraitInspector 
{
    public void DoThing() 
    {
        // This is where I run into my issue, 
        // I need to be able to get the trait that 
        // an instance of the TraitUser class is using to continue.
        TraitUser<> tUser = GetRandomTraitUser()/*Imagine this returns an instance of TraitUser with a random trait, this is where my issue comes in.*/;
    }
}


Solution 1:[1]

If I understand youright, you need get information about generic type T in TraitUser instance in TrairInspector.

public interface IGetTraitInfo
{
    Type GetTraitObjectType();
    object GetTraitObject();
}

public class TraitUser<T> : IGetTraitInfo
{
    private T _thing;

    public void DoThingWithT(T thing) 
    {
        _thing = thing;
    }

    public Type GetTraintObjectType()
    {
        return typeof(T);
    }

    public Type GetTraitObject()
    {
        return _thing;
    }
}

public class TrairInspector 
{
    public void InspectTraitUser(IGetTraitInfo traitUser) 
    {
        Type traitType = traitUser.GetTraintObjectType();
        object data = traitUser.GetTraitObject();
    }
}

Solution 2:[2]

I didn't understand completely but this might help you.

public interface ITrait
{
    string DoSomething();
}

public class Trait<T> where T : ITrait, new()
{
    public string DoSomething()
    {
        ITrait trait = new T();
        return trait.DoSomething();
    }
}

public class TraitUser : ITrait
{
    public string DoThing()
    {
        return "return something";
    }
}

public class TrairInspector
{
    public void DoThing()
    {
        Trait<TraitUser> traitUser = new Trait<TraitUser>();
        traitUser.DoSomething();
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 opewix
Solution 2 Nagaraja S