Inheritance in nested classes C# - c#

fans of beautiful code.
I would like to ask my question by two ways. May be it will be useful to understand me.
1) There is code of 2 classes. One of them is nested. Nested class is used to get access to private fields of other one. I would like to get inherit class B:A{class BUnit:AUnit{}} which has the same functional but else has some more methods and fields in B and BUnits classes. How it can be done?
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Add();
a.Add();
a.Add();
bool res=a[0].Rename("1");//res=true;
res = a[1].Rename("1");//res= false;
Console.ReadKey();
}
}
class A
{
private List<AUnit> AUnits;
public AUnit this[int index] {get {return AUnits[index];}}
public A()//ctor
{
AUnits = new List<AUnit>();
}
public void Add()
{
this.AUnits.Add(new AUnit(this));
}
public class AUnit
{
private string NamePr;
private A Container;
public AUnit(A container)//ctor
{
NamePr = "Default";
this.Container = container;
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (AUnit unt in this.Container.AUnits)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
2) There is two very similar “things” – Class A and Class B. Is it possible to separate their common part, and then “inherit” this two “things” from it ? For example, I would like add some methods like GetUnitsCount() or RemoveUnit() and this methods are common for both. So I should “CopyPaste” this method to A and B but it is not good idea. It will be better to change their common part one time in one place. There is no important how it can be done – inheriting or interfaces or anything else. Important - how?
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Add();
a[0].objB.Add();
a[0].objB.Add();
a[0].objB[0].Val1 = 1;
int res = a[0].objB[0].Val1 + a[0].objB[0].Val2;
Console.ReadKey();
}
}
class A
{
private List<AUnit> Units;
public AUnit this[int index] {get {return Units[index];}}
public A()//ctor
{
Units = new List<AUnit>();
}
public void Add()
{
this.Units.Add(new AUnit(this));
}
public class AUnit
{
private string NamePr;
private A Container;
public B objB;
public AUnit(A container)//ctor
{
NamePr = "Default";
this.Container = container;
this.objB = new B();
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (AUnit unt in this.Container.Units)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
class B
{
private List<BUnit> Units;
public BUnit this[int index] { get { return Units[index]; } }
public B()//ctor
{
Units = new List<BUnit>();
}
public void Add()
{
this.Units.Add(new BUnit(this));
}
public class BUnit
{
private string NamePr;
private B Container;
public int Val1{get;set;}
public int Val2{get;set;}
public BUnit(B container)//ctor
{
NamePr = "Default";
this.Container = container;
this.Val1 = 10;
this.Val2 = 17;
}
public string Name { get { return this.NamePr; } }
public Boolean Rename(String newName)
{
Boolean res = true;
foreach (BUnit unt in this.Container.Units)
{
if (unt.Name == newName) res = false;
}
if (res) this.NamePr = String.Copy(newName);
return res;
}
}
}
Thank you for your attentions.

To answer your first question, the only thing you need to to to have BUnit inherit from AUnit is to qualify AUnit:
public class BUnit : A.AUnit
{
....
}
from there I believe your question is about basic inheritance which works no differently for nested classes. Nested classes are purely for organization - they are not inherited when you inherit the "containing" class.

Related

is this implementation of the Singleton and Object null Patterns Thread Safe?

Im trying to write a simple code to implement the Singleton and object null patterns.
the code should check if the new customer has a name, if yes put it in the real customer, and if not in the fakecustomer.
My focus in this question is: Is the Singleton pattern making my code thread safe in this case?
interface Icustomer
{
string Name { get; }
bool IsNull { get; }
}
class realcustomer : Icustomer
{
public string Name { get; set; }
public bool IsNull { get { return false; } }
public realcustomer(string name)
{
Name = name;
}
}
class fakecustomer : Icustomer
{
public string Name { get { return "customer not available"; } }
public bool IsNull { get { return true; } }
}
class checkifnull
{
public static Icustomer Getcustomer(string name)
{
if (string.IsNullOrEmpty(name))
{
return new fakecustomer();
}
else
{
return new realcustomer(name);
}
}
}
class Singleton
{
private int total = 0;
private static Icustomer cust;
private Singleton() { }
public static Icustomer makecust(string name)
{
if (cust == null)
{
if (string.IsNullOrEmpty(name))
{
cust = new fakecustomer();
}
else
{
cust = new realcustomer(name);
}
}
return cust;
}
public void add()
{
total++;
}
public int getTotal()
{
return total;
}
}
internal class Program
{
static void Main(string[] args)
{
Icustomer new_cust = Singleton.makecust("name");
}
}
each pattern works when implemented on its own, but now i'm trying to use both at the same time.

Iterator pattern, how to make it generic?

I have a iterator pattern. But I want to make it generic. So that you can have strings and numbers. Because now you only can put strings in the list items.
So I have this:
public interface IIterator< out T>
{
void First();
T Next();
bool IsDone();
T CurrentItem();
}
public interface IAggregate< out T>
{
IIterator <T> CreateIterator();
}
}
public class Science : IAggregate<T>
{
private LinkedList<string> Subjects;
public Science()
{
Subjects = new LinkedList<string>();
Subjects.AddFirst("Maths");
Subjects.AddFirst("Comp. Sc.");
Subjects.AddFirst(99);// So this of course fails
}
public IIterator<T> CreateIterator()
{
return new ScienceIterator<T>(Subjects);
}
}
public class ScienceIterator : IIterator
{
private System.Collections.Generic.LinkedList<string> Subjects;
private int position;
public ScienceIterator(LinkedList<string> subjects)
{
this.Subjects = subjects;
position = 0;
}
public void First()
{
position = 0;
}
public string Next()
{
return Subjects.ElementAt(position++);
}
public bool IsDone()
{
if (position < Subjects.Count)
{
return false;
}
else
{
return true;
}
}
public string CurrentItem()
{
return Subjects.ElementAt(position);
}
}
So my question is, is this possible in the default C# collection? Or you have to make your own LinkedList?
Thank you

instance access to class members of inherited abstract

This is theory Thursday I guess.
Shouldn't Main() have access to _XLocal & _YLocal?
using System;
namespace HelloGoodbyeOperator {
public abstract class HGOperator {
public string _greeting { get; set; }
public bool _x { get; internal set; }
public bool _y { get; internal set; }
public static implicit operator HGOperator(bool mode) {
object ret = new object();
if (mode)
ret = new HGOperator_Hello { _greeting = "hello", _XLocal = 10 };
else
ret = new HGOperator_Goodbye { _greeting = "goodbye", _YLocal = 20 };
return (HGOperator)ret;
}
}
public class HGOperator_Hello : HGOperator {
public int _XLocal { get; set; }
public HGOperator_Hello() { _x = true; Console.WriteLine("HGOperator_Hello //" + _XLocal.ToString() + "\\\\"); }
}
public class HGOperator_Goodbye : HGOperator {
public int _YLocal { get; set; }
public HGOperator_Goodbye() { _y = false; Console.WriteLine("HGOperator_Goodbye //", _YLocal, "\\\\"); }
}
class Program {
static void Main(string[] args) {
HGOperator hg = true;
Console.WriteLine(hg._greeting);
test(hg);
Console.WriteLine("");
hg = false;
Console.WriteLine(hg._greeting);
test(hg);
Console.ReadKey();
}
static void test(HGOperator hg) {
if (hg is HGOperator_Hello) {
Console.WriteLine(hg._x);
//Console.WriteLine(hg._XLocal);
} else {
Console.WriteLine(hg._y);
//Console.WriteLine(hg._YLocal);
}
}
}
}
Here is the output
HGOperator_Hello //0\
hello
True
HGOperator_Goodbye //
goodbye
False
I can understand how trying to access hg._YLocal of a HGOperator_Hello type would be a nightmare & vise-versa. But would still think I could get to the respective members with caution.
Also and I will bet this is realted. The two concrete constructors do not have a value for _XLocal & _YLocal on the Console.Writeline()s. Without the .ToString() just a "" is printed. Why not?
Thanks.
The issue is that the compiler doesn't know that hg is a derived type of HGOperator_Hello or HGOperator_Goodbye. So inside your if you need to create another variable and cast it:
if (hg is HGOperator_Hello)
{
var helloHg = (HGOperator_Hello)hg;
Console.WriteLine(helloHg._x);
Console.WriteLine(helloHg._XLocal);
}
else
{
var goodbyeHg = (HGOperator_Goodbye)hg;
Console.WriteLine(goodbyeHg._y);
Console.WriteLine(goodbyeHg._YLocal);
}

Making Validation Generic

I have the following C# code. Here the validations are kept outside the class to satisfy Open – Closed Principle. This is working fine. But the challenge is – the validations are not generic. It is specific to employee class (E.g DateOfBirthRuleForEmployee). How do I make the validations generic for all objects (DateOfBirthRuleForAnyObject).
Note: Make Generic <==> Make Type-Independent
Note: I have NameLengthRuleForEmployee validation also. New validation may come in future.
EDIT
Generic Method Example: Using “OfType” in LINQ
CODE
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee();
employee.DateOfBirth = DateTime.Now;
employee.Name = "Lijo";
DateOfBirthRuleForEmployee dobRule = new
DateOfBirthRuleForEmployee();
NameLengthRuleForEmployee nameRule = new
NameLengthRuleForEmployee();
EmployeeManager employeeManager = new EmployeeManager();
employeeManager.AddRules(dobRule);
employeeManager.AddRules(nameRule);
bool result = employeeManager.validateEntity(employee);
Console.WriteLine(result);
Console.ReadLine();
}
}
public interface IEntity
{
}
public interface IRule<TEntity>
{
bool IsValid(TEntity entity);
}
public class DateOfBirthRuleForEmployee : IRule<Employee>
{
public bool IsValid(Employee entity)
{
return (entity.DateOfBirth.Year <= 1975);
}
}
public class NameLengthRuleForEmployee : IRule<Employee>
{
public bool IsValid(Employee employee)
{
return (employee.Name.Length < 5);
}
}
public class Employee : IEntity
{
private DateTime dateOfBirth;
private string name;
public DateTime DateOfBirth
{
get
{
return dateOfBirth;
}
set
{
dateOfBirth = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
public class EmployeeManager
{
RulesEngine<Employee> engine = new RulesEngine<Employee>();
public void AddRules(IRule<Employee> rule)
{
engine.AddRules(rule);
//engine.AddRules(new NameLengthRuleForEmployee());
}
public bool validateEntity(Employee employee)
{
List<IRule<Employee>> rulesList = engine.GetRulesList();
//No need for type checking. Overcame Invariance problem
bool status = true;
foreach (IRule<Employee> theRule in rulesList)
{
if (!theRule.IsValid(employee))
{
status = false;
break;
}
}
return status;
}
}
public class RulesEngine<TEntity> where TEntity : IEntity
{
private List<IRule<TEntity>> ruleList = new
List<IRule<TEntity>>();
public void AddRules(IRule<TEntity> rule)
{
//invariance is the key term
ruleList.Add(rule);
}
public List<IRule<TEntity>> GetRulesList()
{
return ruleList;
}
}
The challange is for your rules to know which property of what type to validate. You can either provide this by implementing an interface that provides just that as suggested by SLaks or by quessing it dynamically or by providing a concrete rule class with a bit more information on how to access the given property, e.g.:
class NameRule<T> : IRule<T>
{
private Func<T, string> _nameAccessor;
public NameRule(Func<T, string> nameAccessor)
{
_nameAccessor = nameAccessor;
}
public bool IsValid(T instance)
{
return _nameAccessor(instance).Length > 10;
}
}
this ofcourse can be used in the following way:
NameRule<Employee> employeeNameRule = new NameRule<Employee>(x => x.name);
employeeManager.addRule(employeeNameRule);

help me to choose between two designs

// stupid title, but I could not think anything smarter
I have a code (see below, sorry for long code but it's very-very simple):
namespace Option1
{
class AuxClass1
{
string _field1;
public string Field1
{
get
{
return _field1;
}
set
{
_field1 = value;
}
}
// another fields. maybe many fields maybe several properties
public void Method1()
{
// some action
}
public void Method2()
{
// some action 2
}
}
class MainClass
{
AuxClass1 _auxClass;
public AuxClass1 AuxClass
{
get
{
return _auxClass;
}
set
{
_auxClass = value;
}
}
public MainClass()
{
_auxClass = new AuxClass1();
}
}
}
namespace Option2
{
class AuxClass1
{
string _field1;
public string Field1
{
get
{
return _field1;
}
set
{
_field1 = value;
}
}
// another fields. maybe many fields maybe several properties
public void Method1()
{
// some action
}
public void Method2()
{
// some action 2
}
}
class MainClass
{
AuxClass1 _auxClass;
public string Field1
{
get
{
return _auxClass.Field1;
}
set
{
_auxClass.Field1 = value;
}
}
public void Method1()
{
_auxClass.Method1();
}
public void Method2()
{
_auxClass.Method2();
}
public MainClass()
{
_auxClass = new AuxClass1();
}
}
}
class Program
{
static void Main(string[] args)
{
// Option1
Option1.MainClass mainClass1 = new Option1.MainClass();
mainClass1.AuxClass.Field1 = "string1";
mainClass1.AuxClass.Method1();
mainClass1.AuxClass.Method2();
// Option2
Option2.MainClass mainClass2 = new Option2.MainClass();
mainClass2.Field1 = "string2";
mainClass2.Method1();
mainClass2.Method2();
Console.ReadKey();
}
}
What option (option1 or option2) do you prefer ? In which cases should I use option1 or option2 ? Is there any special name for option1 or option2 (composition, aggregation) ?
According to Law of Demeter, Option2. That way you can freely change the implementation of MainClass, You don't have to worry about calling code relying on details of AuxClass1, and indeed can remove it entirely if needed.
EDIT
interface IAuxClass1
{
string Field1 { get; set; }
void Method1();
void Method2();
}
class AuxClass1 : IAuxClass1
{
string _field1;
public string Field1
{
get
{
return _field1;
}
set
{
_field1 = value;
}
}
// another fields. maybe many fields maybe several properties
public void Method1()
{
// some action
}
public void Method2()
{
// some action 2
}
}
public class MyClass : ServiceContainer
{
public MyClass()
{
this.AddService(typeof(IAuxClass1), new AuxClass1());
}
public MyClass(IAuxClass1 auxClassInstance)
{
this.AddService(typeof(IAuxClass1), auxClassInstance);
}
public IAuxClass1 AuxClass
{
get
{
return (this.GetService(typeof(IAuxClass1)) as IAuxClass1);
}
}
}
Original
I tihnk MainClass should derive from AuxClass..
class MainClass : AuxClass1
{
}
I would start with implementing a nice feature of C# called "automatic properties". Instead of writing
private ThisType _myThing;
public ThisType MyThing
{
get { return _myThing; }
set { _myThing = value; }
}
you can write
public ThisType MyThing { get; set; }
and the compiler will generate the exact same IL. On top of this, you can add some options, for example making the setter private:
public ThisType MyThing { get; private set; }
In your case, I would go for option 3:
namespace Option3
{
public AuxClass
{
public string Field1 { get; set; }
public Method1() { ... }
public Method1() { ... }
}
public MainClass
{
public AuxClass Aux { get; private set; }
public MainClass(AuxClass aux)
{
this.Aux = aux;
}
}
}
class Program
{
static void Main(string[] args)
{
Option3.AuxClass = auxClass3 = new Option3.AuxClass();
Option3.MainClass mainClass3 = new Option3.MainClass(auxClass3);
mainClass3.Aux.Field1 = "string2";
mainClass3.Aux.Method1();
mainClass3.Aux.Method2();
}
}
This way, you lock the AuxClass reference once it's set (like in Option 2) while not locking up yourself for changes in the AuxClass interface (like in Option 1).
Decision of choosing design is based on different factors,
Shorter code => Option 1
Monitor activity of each functionality and every access => Option 2, however using linq and expressions, you can write a generalized code that can work with even option 1, but thats too complicated to discuss here.

Categories

Resources