5

I have a Person class :

public class Person 
{
    virtual public long Code { get; set; }
    virtual public string Title { get; set; }       
    virtual public Employee Employee { get; set; }
}

I need to a generic solution for get all properties of Person class without properties by custom class types. Means select Code , Title properties.

typeof(Person).GetProperties();           //Title , Code , Employee
typeof(Person).GetProperties().Where(x => !x.PropertyType.IsClass); // Code

How can I select all properties without custom class types? (Code , Title)

Ehsan
  • 3,431
  • 8
  • 50
  • 70
  • Does "custom type" imply that 3rd party assemblies are custom or are you just looking for types that aren't "yours"? – Steve Danner Aug 21 '12 at 12:21
  • One dilemma here: there is no inbuilt definition of "custom class types", and indeed, `Title` is a `string,` which *is a class* (so you can't just use `.IsClass`) – Marc Gravell Aug 21 '12 at 12:21

2 Answers2

4

One way is to check the ScopeName of the Module of the Type:

typeof(Person).GetProperties().Where(x => x.PropertyType.Module.ScopeName == "CommonLanguageRuntimeLibrary")

since there is no direct way that to tell if a type is built-in or not.

To get some other ideas, see here, here and here.

Community
  • 1
  • 1
sloth
  • 99,095
  • 21
  • 171
  • 219
0

I would suggest using an attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SimplePropertyAttribute : Attribute
{
}

public class Employee { }

public class Person
{
    [SimpleProperty]
    virtual public long Code { get; set; }

    [SimpleProperty]
    virtual public string Title { get; set; }

    virtual public Employee Employee { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        foreach (var prop in typeof(Person)
            .GetProperties()
            .Where(z => z.GetCustomAttributes(typeof(SimplePropertyAttribute), true).Any()))
        {
            Console.WriteLine(prop.Name);
        }

        Console.ReadLine();
    }
}
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • That's a bit high maintenance, though – Marc Gravell Aug 21 '12 at 12:34
  • @MarcGravell That's true, but in the other hand it might help handling some use cases, such as enumerations that are not "custom class types" (not classes at least), depending on what the OP means by "custom class types". – ken2k Aug 21 '12 at 12:45
  • indeed; of course, you could argue from the fact that *in IL/CLI terminology*, enums and structs are still classes. But not in C# terminology, or via `.IsClass` – Marc Gravell Aug 21 '12 at 13:00
  • @drch I do not agree. The OP definition of "custom class type" is pretty vague, I think it's a reliable option to add an attribute to properties that meet its needs. Also, I don't think the downvote is justified. – ken2k Aug 21 '12 at 13:17