Class instantiation from Type

  • Thread starter Thread starter tommasop
  • Start date Start date
T

tommasop

I'm developing a custom server control that should take a datasource
and its Type and from its Type instantiate internal objects to display
data.

MyServerComponent mySrv = new MyServerComponent();
mySrv.DataSource = My.NewsManager.GetObjects();
mySrv.ObjectType = typeof(News);

Internally I would like to be able to do something like this:

((ObjectType)myObj).Title = TitleTbox.Text;

Using ObjectType to instantiate, cast objects to actual object class.

Is it possible?

Is there any workaround?

Thanks

Tommaso Patrizi
 
The relationship between your two blocks of code is a little hazy, so...

You could use reflection:
ObjectType.GetProperty("Title").SetValue(myObj, TitleTbox.Text, null);

Alternatively, if you are talking about windows-forms, then you might be
able to usee bindings to attach the "Text" property of the textbox to the
"Title" property of the object, and it will manage reads and writes for you.

Otherwise - do you have multiple objects with a .Title (and the other
properties)? If so, then interfaces are the way to go - if myObj is always
going to be one of these.

Marc
 
Sorry - missed a bit; to instantiate via reflection (using the default
public ctor), you can use:

ObjectType.GetConstructor(Type.EmptyTypes).Invoke(null);

However, in 2.0 another option is to use generics constrained with the new()
condition, e.g.

public void CreateAndBindToObject<T>() where T : new() {
T t = new T();
// do some things with you new T instance
}

e.g. call CreateAndBindToObject<SomeClass>(); note that this won't provide
the properties (.Title etc) unless you for instance also restrict to an
interface:

public void CreateAndBindToObject<T>(string title) where T : ISomeInterface,
new() {
T t = new T();
t.Title = title; // assuming ISomeInterface defines "string Title {set;}"
// do some things with you new T instance
}

Marc
 

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

Back
Top