I\'ve got such a problem. I\'m a beginner in C#. I have an object array (various classes) and in one place of application I want to modify fields like an age or name. Construct
First you need to cast the object to the type you're intending to work with.
If you work with type object
, it has only a limited amount of properties and methods. To use property age
, you first need to cast it to the corresponding type that has that property. For instance something like this:
static Object[] prac = new Object[10];
public static void Main(string[] args)
{
SpecificType myObject = prac[0] as SpecificType; // returns null if not successful
if (myObject != null)
myObject.age = 21;
}
HOWEVER, I'm not convinced you're doing the right thing here. I'd personally avoid type object
unless absolutely there would be no other way of doing it (and that is very rare in my code). C# is a strongly-type language and by using object
you're prone to errors all over the place.