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
It's an array of objects and as the error message suggests, 'object' does not contain a definition for 'age'
You need to declare your array with the type that has age
field or property.And the you can modify it whatever you want. For example:
class Person
{
public string Name { get; set; }
}
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.
Object is the base class for all classes in .Net.
Just cast the required value to the required typed class. Or Create a list with the right type instead of object.
You have to use an array of your class instead of Object
which is the base type of all classes.
static MyClass[] prac = new MyClass[10];
or you have to cast it:
MyClass mc = (MyClass) prac[0];
mc.age = 21;
You need to cast your member to the class type that contains the age. I'll just assume that your class name is Person
and that is has a age
member :
static Object[] prac = new Object[10];
public static void Main(string[] args)
{
((Person)prac[0]).age = 21;
}
Important to note are the brackets : (Person)prac[0]
is the cast part, you cast the Object
prac[0]
to a Person
object. The outer brackets ((Person)prac[0])
are there so that the code is taken as a Person
object, instead of a regular Object
.
Object
doesn't have property age
.
All Object
's properties and methods are stated here.