Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to tell if an object is of a custom class or native type /.NET class?

Tags:

c#

.net

types

class

I have this class

public class MyViewModel {
  public MyClass Thing { get; set; }
  public int Id { get { return Thing.Id; } }
  public string Name { get { return Thing.Name; } }
}

I noticed when I bind it to an ASP.NET GridView, it automatically omits Thing, and for a good reason (ie. because otherwise it will only show the meaningless "MyNamespace.MyClass" in all rows)

I am trying to do a similar thing in this method.

public static string ConvertToCsv<T>(IEnumerable<T> items)
{
  foreach (T item in items)
  {
    if(item is not a native/.NET class) // <-- How do you do this?
      continue;
    else // If it is a string/int/bool/DateTime or something meaningful
    {
      ...
    }
  }
}
like image 971
Aximili Avatar asked Feb 14 '13 03:02

Aximili


1 Answers

Not sure about performance, but you could use somthing along the lines of

if(item.GetType().Namespace.StartsWith("System")) 
{
   // do stuff
}

Or filter before looping

public static string ConvertToCsv<T>(IEnumerable<T> items)
{
    foreach (T item in items.Where(i => i.GetType().Namespace.StartsWith("System")))
    {

    }
}

Edit: after a quick test the method above has some flaws, If your object is nullable (MyViewModel?) it will be picked up in this check (System.Nullable<MyViewModel>).

So perhaps you could use:

public static string ConvertToCsv<T>(IEnumerable<T> items)
{
    foreach (T item in items.Where(i => i.GetType().Module.ScopeName.Equals("CommonLanguageRuntimeLibrary")))
    {

    }
}

Another edit: There seems to be some issue with the last method also, But this one below is by far the fastest and most reliable, We just create a list of the System.Objects from the Assembly, and check if your item object is in that list.

private List<Type> _systemTypes;
public List<Type> SystemTypes
{
    get
    {
        if (_systemTypes == null)
        {
            _systemTypes = Assembly.GetExecutingAssembly().GetType().Module.Assembly.GetExportedTypes().ToList();
        }
        return _systemTypes;
    }
}

public static string ConvertToCsv<T>(IEnumerable<T> items)
{
    foreach (T item in items.Where(i => SystemTypes.Contains(i.GetType())))
    {
         // is system type
    }
}
like image 114
sa_ddam213 Avatar answered Oct 19 '22 12:10

sa_ddam213