Multiple types in an array  
Author Message
szolDat





PostPosted: Visual C# Language, Multiple types in an array Top

Hello!

I'd like to put two different classes' instances into an array. (Both are child classes, derived from a base class.) The problem is, you have to specify a type for the array itself, but I don't know what to do if I have to store more then one type in it. Will it work if I use the base class as array type, and if yes, please give me an example. Probably it won't since the base class doesn't contain the child classes' fields and methods.

I also would like to know if it's possible to store even more types, like "string", "int", "instance of a class" all in one array.

I tried to understand structures, but I couldn't get closer to the solution. Anyway, I'm in college and we didn't learn anything about structures yet, so please don't post possible solutions which include that. (Also, I was wondering how to use structures in Visual Studio 2005, since it creates different files for different classes, and I'm wondering how to include two classes in one structure. You have to use structures where the Main() is, right )

If you couldn't understand my questions, please tell me, and I'll try to rephrase my post.



Visual C#20  
 
 
Ken_L





PostPosted: Visual C# Language, Multiple types in an array Top

You might have to rephrase because, I can't see a reason to do what you are asking. You can add all your class's properties to an array. But it sounds like you might be confused on BaseClass

Most of us don't bother inheriting a class unless there is a specific reason. Instead we instantiate the class... With the logic I have below you can create you array in the base class, and both class1 & 2, can add their properites to the array

Is this what you are leading too

Class1
{

BaseClass BC = new BaseClass();
public property

}

Class2
{

BaseClass BC = new BaseClass();
Class1 C1 = new Class1();
C1.property

}

BaseClass
{

public array

}



 
 
szolDat





PostPosted: Visual C# Language, Multiple types in an array Top

Okay, then I'll try to explain my problem through an example. Here are some (not actual!) classes.

//My BaseClass is a field and a method
    class BaseClass
    {
        int baseclassint;
        public void baseclassmethod()
        {
            //Empty
            ;
        }
    }


//My classes derived from BaseClass
    class InheritingClass1 : BaseClass
    {
        int inheritingclassint;
        public void inheritingclassmethod()
        {
            //Empty
            ;
        }
    }


    class InheritingClass2 : BaseClass
    {
        int inheritingclassint;
        public void inheritingclassmethod()
        {
            //Empty
            ;
        }
    }

//My class which contains Main()
class Program
    {
        static void Main(string[] args)
        {
            InheritingClass1 class1instance = new InheritingClass1();
            InheritingClass2 class2instance = new InheritingClass2();
//This is the array in which I want to store my two objects: "class1instance" and "class2instance", so I could access all of their inherited and not inherited fields and methods. The problem is, that an array accepts only one type, in this case "TypeofArray" as shown below. I need to store both instances in ONE array. Because the teacher said so...

            TypeofArray[] mainarray = new TypeofArray[2];
        }
    }

I've been searching the net for about 3 hours and I found that an ArrayList can contain pretty much anything, and it's items can be accessed by their index numbers. Seems good so far, though i'm nowhere near finishing my program, so I might end up stuck again. Thanks for trying to help, Ken_L.

I have a problem now with exception handling, though I wouldn't like to start another topic, maybe I find this out myself soon enough.
I can catch an exception but I can't find a keyword or command which returns me to the try block and tries again, until there where no exceptions in that block. I have a solution for this, which is to surround the try-catch with "while(variable= 0)", because there is an assignment in the try block and if the "variable" stays 0, the while block executes again. I'm wondering if there is anything better than this clumsy solution.


 
 
RizwanSharp





PostPosted: Visual C# Language, Multiple types in an array Top

If all objects are from the same Base class then you can create an array of the Base class and stor the Child Class's objects in it. Like:

class SomeBaseClass

{

public void SomeBaseMethod()

{

}

}

class SomeChildClass1 : SomeBaseClass

{

public void SomeChildMethod1()

{

}

}

class SomeChildClass2 : SomeBaseClass

{

public void SomeChildMethod2()

{

}

}

To Store the objects of Child Classes in a single aray you can write something like this:

SomeChildClass1 someChildClass1 = new SomeChildClass1(); // Create an object of SomeChildClass1

SomeChildClass2 someChildClass1 = new SomeChildClass2(); // Create an object of SomeChildClass1

SomeBaseClass[] someBaseClassArr = new SomeBaseClass[2]; // Create an Array to store both objects..

someBaseClassArr[0] = someChildClass1; // Insert someChildClass1 at first Index

someBaseClassArr[1] = someChildClass2; // Insert someChildClass2 at second Index

Retrival is a bit tricky and can be error prone if you make a mistake obseve this:

SomeChildClass1 someChild1TempObject = (SomeChildClass1 ) someBaseClassArr[0]; // Because it was stored as Base Object so for putting it back to the original object you need to cast back it...

SomeChildClass2 someChild2TempObject = (SomeChildClass2 ) someBaseClassArr[1]; // Because it was stored as Base Object so for putting it back to the original object you need to cast back it...

Both Statmenets will work fine:

How Ever the following line will create an Invalid Exception at Runtime:

SomeChildClass2 someChild1TempObject = (SomeChildClass2 ) someBaseClassArr[0]; // Error! because you stored object of SomeChildClass1 at Index 0 so it cannot be converted to object of SomeChildClass2...

To Avoid this Exception We use as Keyword as follow:

SomeChildClass2 someChild1TempObject = someBaseClassArr[0] as SomeChildClass2;

if(someChild1TempObject == null) // Means Casting was Invalid

{

///

}

else // Parsing was Successfull

{

}

Above Solution works smooothly without any Runtime Error

So The concept here is that you can put any object of child class in the object of BaseClass but for getiting that object back to original class's object you need to parse it back and you should use as keyword to work safely and knowing if the casting was OK or Not.

You were asking about others, Int, Float etc....

To store all Type of objects in a single Array you can use:

object[] objArr = new object[10];

You can story any type of object like int, SomeChildClass, SomeBaseClass, String, Float etc...... Because The base class of all types in .Net is the object class but you should check for safety when getting back the object to its real type.....

ArrayList also works on the same Rule, it stores all types as objects and you need to convert them back when you need any item back:

Here is an example:

ArrayList arrayList = new ArrayList();

arrayList.Add(1); //Store Int

arrayList.Add("Rizwan"); //Store string

arrayList.Add(someChildClass1); //Store object of someChildClass1

The benefit of using ArrayList Collection over Array is that it's size is Dynamic and it expands at runtime when you insert more objects in it.....

I hope this little tutorial for you goes in Right Direction to help you :).

Best Regards,

Rizwan



 
 
szolDat





PostPosted: Visual C# Language, Multiple types in an array Top

Thank you, i managed to get help from somewhere else, but your post is the solution anyway.