Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing class fields throughout generic function (.Net Framework 4.8)

First, I have this function that return true if the name is in the class:

public bool hasName<T>(List<T> Data, string name, Func<T, string> ClassName)
{
    foreach (T entry in Data)
    {
        if (ClassName(entry) == name)
        {
            return true;
        }
    }

    return false;
}

And it’s called using:

hasName(Data, name, x => x.name)

The problem is, that i have another function that uses HasName but doesn’t know about the field name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public List<T> MergeClasses<T>(List<T> Pri, List<T> Sec, Func<T, string> ClassName)
{
    List<T> result = new List<T>();

    result.AddRange(Pri);

    foreach (T entry in Sec)
    {
        if (!new Functions().hasName(result, ClassName(entry), x => x.name))
        {
            result.Add(entry);
        }
    }

    return result;
}

How can i solve this?

>Solution :

You would need an interface or base-class to use as a generic constraint; for example:

interface IHazHame {
    string Name {get;} // note property, not field
}

then your type with .name would need to implement that:

class Foo : IHazName {
    // ...
}

and you can restrict your generic method to T that satisfy this:

public List<T> MergeClasses<T>(List<T> Pri, List<T> Sec, Func<T, string> ClassName)
    where T : IHazHame
{
  // ... x => x.Name
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading