Delyew
Delyew

Reputation: 15

Can't access class field in another class

public class Vector
    {
        public int[] row = new int[2];
        public Vector(int x, int y)
        {
            this.row[0] = x;
            this.row[1] = y;
        }
        public int[] Row
        {
            get
            {
                return row;
            }
        }
    }
public class Matrix<Vector>
    {
        public Vector[] rows = new Vector[2];
        public Matrix(Vector v1, Vector v2){
            this.rows[0] = v1;
            this.rows[1] = v2;
        }
        public void Transform()
        {
            foreach (Vector v in rows)
            {
                Console.WriteLine(v.row[0]);
            }
        }
    }

I'm getting 'Vector' does not contain a definition for 'row' and I have no idea why. It's set to public and I'm iterating over vector objects. What am I doing wrong here?

This is my first time using c#, coming from python so please don't mind the code if it doesn't make sense. Just toying with classes and syntax

Upvotes: 0

Views: 81

Answers (2)

Amit
Amit

Reputation: 1857

here as you have written in your question,

public class Matrix<Vector>

means, your class Matrix is generic, and whatever type you will pass while creating an instance of Matrix, code of this class will take that type as Vector .

Note that your class Vector is total different type than the type Vector in Matrix class.

For ex.

if your create an object of matrix like this,

Matrix<string> m = new Matrix<string> ("amit", "maheshwari");

this will be valid and for this instacne of Matrix, Vector will be string. and yes string does not contain a definition for 'row' and so does Vecotr.

So, maybe you are misusing this class.

Or if you have created this class by your self and you want to perform what you have shown in question, there is no need to make this class generic.

public class Matrix
{
    //so now this array of vector will be of class Vector
    public Vector[] rows = new Vector[2];
    public Matrix(Vector v1, Vector v2){
        this.rows[0] = v1;
        this.rows[1] = v2;
    }
    public void Transform()
    {
        foreach (Vector v in rows)
        {
            Console.WriteLine(v.row[0]);
        }
    }
}

Upvotes: 3

Omid Nasri
Omid Nasri

Reputation: 179

public class Matrix<TVector> where TVector : Vector
{
    public TVector[] rows = new TVector[2];
    public Matrix(TVector v1, TVector v2)
    {
        this.rows[0] = v1;
        this.rows[1] = v2;
    }
    public void Transform()
    {
        foreach (TVector v in rows)
        {
            Console.WriteLine(v.row[0]);
        }
    }
}

Thank you for John and other friends for reply quick answer. you must use TVector.

Upvotes: 0

Related Questions