How to use TypeOf()?

B

Brett Romero

I have a collection that holds DataGridTextBoxColumn types, which I
then bind to a DataGrid. I loop through all of the
DataGridTextBoxColumn that were created and add them to the collection
like this

for(int i=0; i<dataGridStyleColumnCollection.Count; i++)
{

gridTableStyle.GridColumnStyles.Add((DataGridTextBoxColumn)dataGridStyleColumnCollection);
}

Sometimes, I'll have a DataGridBoolColumn, which breaks the above code.
I'm trying to put in a conditional that checks the type. This always
gives a warning:

The given expression is never of the provided
('System.Windows.Forms.DataGridBoolColumn') type

[the expression]
if(dataGridStyleColumnCollection.GetType() is DataGridTextBoxColumn)

gridTableStyle.GridColumnStyles.Add((DataGridTextBoxColumn)dataGridStyleColumnCollection);

[In the debugger while looping]
- dataGridStyleColumnCollection.GetType() {System.RuntimeType} System.RuntimeType

+ System.Type {"System.Windows.Forms.DataGridBoolColumn"} System.Type

The debugger shows it is of the provided type. Neither of the above
conditionals ever run. They always evaluate to false. What does the
compiler and debugger say two different things?

Should I use something else to determine the column type?

Thanks,
Brett
 
J

Jon Skeet [C# MVP]

Brett Romero said:
I have a collection that holds DataGridTextBoxColumn types, which I
then bind to a DataGrid. I loop through all of the
DataGridTextBoxColumn that were created and add them to the collection
like this

[the expression]
if(dataGridStyleColumnCollection.GetType() is DataGridTextBoxColumn)


The debugger shows it is of the provided type. Neither of the above
conditionals ever run. They always evaluate to false. What does the
compiler and debugger say two different things?

Because what you're asking is whether the type System.Type is an
instance of DataGridTextColumnBox, which it never is. You're sort of in
a half-way house between:

if(dataGridStyleColumnCollection.GetType() ==
typeof(DataGridTextBoxColumn))

and

if(dataGridStyleColumnCollection is DataGridTextBoxColumn)

Either of those would work (although the first one won't "match" if you
give it an instance of something derived from DataGridTextBoxColumn.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top