Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to realize "Reference Array"

Status
Not open for further replies.

SonicChen

Programmer
Feb 14, 2004
62
0
0
CN
Sometimes we don't want to instantiate the class when creating this class array. there exist pointer array in c or c++. example(c++):
class Example
{
}
void main()
{
Example* PointerArray[5]; // uninstantiated
PointerArray[0] = new Example; // instantiate now
}
but we have to instantiate the class in C# when creating array.
class OuterEx
{
class InnerEx
{
}
static void main()
{
InnerEx[] PointerArray = new InnerEx[5];
}
}
for reference is not an independent type in C# and we don't want to use pointer(unsafe code) in most program;
so i have one idea to solve this problem:
class OuterEx
{
class InnnerEx
{
}
class RefEx
{
InnerEx Ref;
}
static void main()
{
RefEx[] RefArray = new RefEx[5];
RefArray[0].Ref = new InnerEx();
}
}
If we don't want to write .Ref every time, we have to write a type convertion method. after all it's real inconvinient.
Anybody can tell me how to solve this problem or there exist any solution i havn't found in C#.
 
one solution here myself, use "object key word" to create the array and then convert the class to object.
 
When you say
Code:
 InnerEx[] PointerArray = new InnerEx[5];
you're not making 5 instances of InnerEx, you're just creating an array with 5 slots for InnerEx objects. All of the elements of the array will be null. You still need to instantiate the objects yourself.
 
Code:
In C++ you have:
class B{};
class C: public B{};
class D: public C{};
class F{};
B *p[5];
p[0]= new B();
p[1]= new C();
p[2]= new D();
p[3]= new F(); // Error 
---
In C# you can do the following (because the class type is derived from the 'object' type ):
public class B{}
public class C:B{}
public class D:C{};
public class F{}
object[] ar = new object[5];
ar[0]= new B();
ar[1]= new C();
ar[2]= new D();
ar[3]= new F();

or instead to say:
B b1 = new B();
C c1 = new C();
D d1 = new D();
F f1 = new F();

you can do:
Hashtable ht = new Hashtable();
ht.Add("b1",new B());
ht.Add("c1",new C());
ht.Add("d1", new D());
ht.Add("f1",new F());
In the both cases use GetType() to determine the type of the object:
-obislavu-
 
ok, i'm sorry to have deserted this forum for 1 week. so i can't read the valuable replys above in time and express my appreciation. now i learn much.
i have tested all the views above and they really do.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top