LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8818

typeof() parameter - how does it work?

In the Code below:

string GetName(Type type)    
{       
    return ((type)this.obj).Name;    
}    

void Run()    
{       
    string name = GetName(typeof(MyClass));    
}

Im getting a "The type or name space cannot be found (are you missing using a directive or assembly reference?)" error. What should I do to correct this?

Upvotes: 1

Views: 2627

Answers (2)

VdesmedT
VdesmedT

Reputation: 9113

You can't cast to an instance !

type is a instance of the Type class, if you want to cast to certain Type, use Generics

void GetName<T>() where T : IObjectWithName { return ((T)this.object).Name; }

then you can call

string name = GetName<MyClass>();

If that makes sens.

Upvotes: 7

Simone
Simone

Reputation: 11797

You can't do like this, you need Reflection to do something like what you are asking for:

void Update(Type type)
{
    PropertyInfo info = type.GetProperty("Name");
    string name = info.GetValue(info, null);
}

Upvotes: 1

Related Questions