C#
public class clsb
{
public string subjectName = "";
public string mainsubject()
{
return subjectName;
}
}
public class clsA : clsb
{
public string subjectName = "";
public string Allsubject()
{
return subjectName;
}
}
private void getdata()
{
clsA obj = new clsA();
//base and derived class
obj.subjectName = "English";
string A1 = obj.mainsubject();
string A2 = obj.Allsubject();
}
Prasad RaveendranRank #320 · 7.8K reputationPosted May 31, 2023, 10:52 AM EDT
In C#, when you declare a new variable with the same name in a derived class, it effectively hides the base class variable. Therefore, you cannot directly access the base class variable using an instance of the derived class.
If you need to access the base class variable, you can create a property or a method in the base class to provide access to that variable.
sample project attached for your perusal. I created a console application in .NET 7.0. Please do let me know if there are any issues
Rajkiran SwainRank #165 · 14.4K reputationPosted May 31, 2023, 7:31 AM EDT
public class clsb { public string subjectName = ""; public string mainsubject() { return subjectName; } } public class clsA : clsb { public new string subjectName = ""; public string Allsubject() { return base.subjectName + " " + subjectName; } } private void getdata() { clsA obj = new clsA(); // Assign values to the subjectName variable in both classes obj.subjectName = "English"; obj.mainsubject(); // Returns the value of subjectName in the base class obj.Allsubject(); // Returns the concatenated value of subjectName in both classes }