473,405 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

creating new instance though reflection

Hello,
I'm new to C# but so far I didn't find big problems, except for
Reflection. I coudn't find any good material in internet where to study
it. If anyone knows about some documents, blogs or stuff, please let me
know.

My problem is that I have to create a new instance of a class, given a
type and a name (object's id) as parameters. The constructor of such
type has no parameters.

Type t;
string id;
ConstructorInfo ci = t.GetConstructor(new Type[] { });
ci.Invoke(null); // this creates the instance but how to bind it to id?
// I know there's a class named Binder, but how do
I have to use it?

Obviously, trying:
t id = ci.Invoke(null);
is not correct for 2 reasons: t is used as a type, while it's a
variable; secondly id is a string, not an identifier.

I tried also Activator.CreateInstance(m_class): what's the different
between this and the previous way?

Finally I need to know if the id (that I have as string variable), is
already binding another object, so that I can change it to do my work.

Thank you in advance.

Alessandro

Dec 22 '06 #1
4 1807
"binding" doesn't apply here... can you clarify what you mean with the
"id is a string not an identifier"? This might mean you need to find
the field first...

ci.Invoke() should return the instance, but unless you are using
generics, all you can do is treat it as an object, i.e. object id =
ci.Invoke(null);

However, if you are talking about a paramererless constructor, then in
2.0 generics is the answer:

public static void SomeMethod<T>() where T : new() {
// do some work
T t = new T();
// do something with T...
}

of course, in the above you can't do much with t by itself, unless you
a: are putting it into an existing collection of Ts, or b: you know
that T supports certain features:

public static void SomeMethod<T>(IList<Tlist) where T : new(),
ISomeInterface {
T t = new T();
list.Add(t);
t.SomeMethod();
}

If I understand your intent ("id as a string"), then another trick
might be:

public static void RecreateField<T>(ref T field) where T : new() {
field = new T();
}

This then allows you to call things like
"RecreateField(someTypedField);" and it will just work... of course,
unless you are doing something else in that code block it would be
easier to just type "someTypedField = new FieldType();"... so can you
clarify?

Marc
Dec 22 '06 #2
If you want to assign a class level field named with the contents of the id
string then you will need to call something like this:

Type t;
string id;
ConstructorInfo ci = t.GetConstructor(new Type[] { });
object newob = ci.Invoke(null);
this.GetType().GetField(Id, System.Reflection.BindingFlags.FlattenHierarchy
| System.Reflection.BindingFlags.Instance).SetValue( this,newob);
--
Ciaran O''''Donnell
http://wannabedeveloper.spaces.live.com
"bowser" wrote:
Hello,
I'm new to C# but so far I didn't find big problems, except for
Reflection. I coudn't find any good material in internet where to study
it. If anyone knows about some documents, blogs or stuff, please let me
know.

My problem is that I have to create a new instance of a class, given a
type and a name (object's id) as parameters. The constructor of such
type has no parameters.

Type t;
string id;
ConstructorInfo ci = t.GetConstructor(new Type[] { });
ci.Invoke(null); // this creates the instance but how to bind it to id?
// I know there's a class named Binder, but how do
I have to use it?

Obviously, trying:
t id = ci.Invoke(null);
is not correct for 2 reasons: t is used as a type, while it's a
variable; secondly id is a string, not an identifier.

I tried also Activator.CreateInstance(m_class): what's the different
between this and the previous way?

Finally I need to know if the id (that I have as string variable), is
already binding another object, so that I can change it to do my work.

Thank you in advance.

Alessandro

Dec 22 '06 #3
Marc,

object id = ci.Invoke(null);

is incorrect because the type of 'id' is 'string'. (The compiler says:
"A local variable named 'id' cannot be declared in this scope because
it would give a different meaning to 'id', which is already used in a
'parent or current' scope to denote something else")

But that would be exactly what I wanted to do: create an object whose
name is the value of 'id'. For example if id="foo" and t="Foo", I want
to create an object 'Foo foo', that is: through reflection, I want to
get the equivalent of
Foo foo = Foo();

The right member ('Foo();') is translated as ...'ci.Invoke(null);'
but the left member remains a problem for me.

I hope I've been clear this time.

Thank you very much.

Alessandro

Dec 22 '06 #4
In the example I meant
Foo foo = new Foo();

I want to create the instance in a particular namespace, say 'ns',
which is not the one where I put the code under discussion.

Finally I recall the second problem: to check if 'foo' already exist
(whatever it's its type) given a namespace.

Dec 22 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Carl Rosenberger | last post by:
Hi all, I would like to create an instance of a struct with reflection. The way I am used to doing this with classes: - get a ConstructorInfo from the Type - call Invoke() However, if a...
3
by: Bisbal | last post by:
Hi, I'd like to know if it is possible to create a form type from a string. My case: I have a DataTable with forms names (i.e frm_001_UserInfo.cs), and I'd like to create an instance of that...
2
by: salportaro | last post by:
Hello: Here is the situation. VB.NET I have several forms and I have a XML file that can start with a particular for for debugging/layout reasons. This is a mdi project. Normaly you would...
16
by: tshad | last post by:
This is a little complicated to explain but I have some web services on a machine that work great. The problem is that I have run into a situation where I need to set up my program to access one...
3
by: Chris Pratt | last post by:
I'm sorry to ask such a fundamental question, but is it possible to create a copy of an object in VB.Net 2005? I have an app which, on load, creates an instance of a class, into which it reads a...
8
by: Ympostor | last post by:
Why can't I do this (it gives a syntactic error):? foreach (System.Reflection.PropertyInfo oProp in oObject.GetType().GetProperties()) { if ((oProp.PropertyType.IsGenericType) &&...
26
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is...
7
by: colin | last post by:
Hi, How can I use a delegate that I can set to call a non static function but of any instance of the class ? eg class TypeTeader<T> { delegate T readDelegate<T>();
19
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I'm doing my c# more and more like i used to code c++, meaning i'm casting more often than creating an instance of objects. like : protected void gvOrderDetailsRowDataBound(object sender,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.