1
Answer

How to use class as a data type?

Jason Anderson

Jason Anderson

13y
1.3k
1
I have a user-defined data type "ClassA".  I get an error when trying to set value of Attribute1.Attribute2.

public class Class1
{
public struct structA
{
        private int value1;
        
        public ClassA Attribute1
        {
                get{return value1;}
                set{value1=value;}
        }
}
public ClassA
{
        private int value2;

        public int Attribute2
        {
                get{return value2;}
                set{value2=value;}
        }
}

public ClassB
{
        public void GetData()
        {
                ...
                ...
                structA.Attribute1.Attribute2 = 10;
                ...
                ...
        }
}
}

I get an <undefined value> everytime I try to get or set Attribute1.Attribute2....Any ideas?

Thanks in advance.

Jason
Answers (1)
0
Vulpes

Vulpes

NA 98.3k 1.5m 13y
I've had to change a few things to get it to compile, but the following now works fine:

using System;

public class Class1
{
   public struct StructA
   {
        private ClassA value1; // needs to be of type ClassA rather than int
        
        public ClassA Attribute1
        {
             get{return value1;}
             set{value1=value;}
        }
   }

   public class ClassA
   {
        private int value2;

        public int Attribute2
        {
             get{return value2;}
             set{value2=value;}
        }
   }

   public class ClassB
   {
        public void GetData()
        {
             StructA structA = new StructA();
             ClassA c = new ClassA();
             structA.Attribute1 = c; 
             structA.Attribute1.Attribute2 = 10;
             Console.WriteLine(structA.Attribute1.Attribute2); // 10
        }
   }
}

class Test
{
   static void Main()
   {
      Class1.StructA sa = new Class1.StructA();
      Class1.ClassA ca = new Class1.ClassA();
      Class1.ClassB cb = new Class1.ClassB();
      ca.Attribute2 = 3;
      sa.Attribute1 = ca;
      Console.WriteLine(sa.Attribute1.Attribute2); // 3
      cb.GetData(); 
      Console.ReadKey(); 
   }
}
Accepted