Chris
Chris

Reputation: 28064

Why does this code tell me the type or namespace could not be found?

Given the following code:

var property = typeof(TEntity).GetProperty("Id");
var temp = (property.PropertyType)id;

VS underlines 'property' in the second line and tells me the type or namespace cannot be found. Why? I've tried with and without using System.Reflection at the top and get the same result.

I was able to work around it by using Convert.ChangeType(id, property.PropertyType), but I'm curious what about the C# spec makes the previous code invalid.

Upvotes: 0

Views: 184

Answers (2)

Pencho Ilchev
Pencho Ilchev

Reputation: 3241

It expects a type (not variable of type System.Type but actual type) between the parentheses, but such type (property.PropertyType) doesn't exist. To prove this add this to your code:

public class property
{
    public class PropertyType
    {

    }
}

Now, the compiler will be satisfied but this is probably not what you want to do.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500675

You're trying to cast via something which is only known at execution time. C# doesn't work like that. The type part of a cast isn't "an expression which evaluates to a Type reference" - it's the name of a type or type parameter.

It's not clear what you're trying to achieve here, but you're not going to be able to do it via casting like that. What do you expect the compile-time type of temp to be? Are you aware that var is just compile-time type inference, not dynamic typing?

If you can give us more information about what you're trying to achieve, we may be able to help you more.

Upvotes: 1

Related Questions