+ 1

Why does the generic variable var doesn't have access to the instance variable "owner"?

internal class Program { private static void Main(string[] args) { BankAccount account1 = new BankAccount("Harish", "1212121", "1222"); var list = new List<BankAccount> {}; list.Add(account1); BankAccount account2 = new BankAccount("vardhan","adsfd","2323"); list.Add(account2); display_elements(list); } public static void display_elements<T>(List<T> l){ foreach(T var in l){ Console.WriteLine(var.owner); } } }

12th Sep 2023, 1:52 PM
Y AD Ù
Y AD Ù - avatar
1 Respuesta
+ 2
Got the answer. My explanation, incase if someone finds its useful: Here, the variable "var" is a generic variable ie., it's type isn't defined previously( its just general (T) ). Since var could be of any data type int, string, char anything the compiler doesnt know if it is an object ( which in this case it is an object of the BankAccount Class) wouldn't provide any knowledge of the existence of object variable like "owner" (or other object variables). Hence the compiler fails to identify the variable "var.owner".
12th Sep 2023, 3:35 PM
Y AD Ù
Y AD Ù - avatar