I have a DataGrid that is given a List, which can be either of type Foo, Bar, or Baz. Later on, I need to extract that data to save it, and to do so I need to know the type of the object inside the List that was set as ItemsSource. I have tried to use GetType, didn't work, trying to do if(GridType is List<Foo>) for example produces the following warning:
The given expression is never of the provided ('System.Collections.Generic.List<Foo>') type
And I couldn't find anything on this error. Searched SO too, couldn't find anything. Is there a way to do what I am trying to do? Or even, a better way than simply getting the type directly?
EDIT:
Ignoring all the boiler plate code (using etc..)
Assume we have created a DataGrid to later add it to the window
public class Foo
{
  public int SomeVar { get; set; }
}
public class MainWindow : Window
{
  public MainWindow ()
  {
  List<Foo> Foos = new List<Foo> ();
  Foos.Add (new Foo ());
  Foos.Add (new Foo ());
  DataGrid SomeDataGrid = new DataGrid ();
  SomeDataGrid.ItemsSource = Foos;
  Type DataGridType = SomeDataGrid.ItemsSource.GetType ();
  if (DataGridType is List<Foo>) //< Error 
    {
    // do stuff
    }
  }
}
 
  
                     
                        
You're mixing two things - is to check whether an object is of the given type, and GetType() which returns the Type reference. The type of DataGridType is Type, and a Type object is never an instance of List<Foo>. (Imagine casting DataGridType to List<Foo> - what would that mean?)
You want either:
if (DataGridType == typeof(List<Foo>))
... which will check whether the type is exactly List<Foo> or:
if (DataGridType.ItemsSource is List<Foo>)
... which will check whether the type is assignable to List<Foo>.
Alternatively, if you would be casting in the if body:
List<Foo> listFoo = DataGridType.ItemsSource as List<Foo>;
if (listFoo != null)
{
    // Use listFoo
}
 
                    See more on this question at Stackoverflow