Reputation: 11730
I have the following code:
public static IList<SortOption> SortValues()
{
var sortValues = (from prop in typeof(SolrSchemaApp1).GetProperties(BindingFlags.Instance | BindingFlags.Public)
where Attribute.IsDefined(prop, typeof(SolrSortAttribute))
select new SortOption(prop.Name)).ToList();
return sortValues;
}
where SolrSchemaApp1 is a class derived from an interface called ISolrDocument.
I want to pass in an instance of SolrSchemaApp2 and make my code select the sort properties from that one instead of SolrSchemaApp1. In effect, I want to do this:
public static IList<SortOption> SortValues(ISolrDocument schemaToScan)
{
var sortValues = (from prop in typeof(schemaToScan).GetProperties(BindingFlags.Instance | BindingFlags.Public)
where Attribute.IsDefined(prop, typeof(SolrSortAttribute))
select new SortOption(prop.Name)).ToList();
return sortValues;
}
All I have done is replaced the hard coded SolrSchemaApp1 with a variable of a different type. However, I get the error
The type or namespace name 'schemaToScan' could not be found (are you missing a using directive or an assembly reference?)
I'm struggling with the syntax of using GetProperties on an arbitrary class.
How do I use Linq to scan the properties of the class that I pass in as a parameter?
Upvotes: 0
Views: 175
Reputation: 1063318
schemaToScan
is not a type (it is a parameter), so typeof(schemaToScan)
makes no sense. You have 3 options, all of which have slightly different meanings:
1: hard-code to typeof(ISolrDocument)
if the property is on the interface
2: use schemaToScan.GetType()
if the property is on the concrete type of the implementing object
3: make it a generic method, and use typeof(T)
if the property is on the declared type of the variable (not object) being passed:
public static IList<SortOption> SortValues<T>(T schemaToScan)
where T : ISolrDocument
{ ... }
Upvotes: 1
Reputation: 28701
First off, use schemaToScan.GetType()
instead of typeof(schemaToScan)
-- typeof
is used to get the Type
for a type name. Use GetType()
for getting the Type
of an instance.
Upvotes: 0
Reputation: 60503
replace typeof(schemaToScan)
by
schemaToScan.GetType()
schemaToScan is an instance of a type, not a type.
Upvotes: 5