Is there a way to make C# inner class instances specific to the instance of the outer class. For example, is there way to do something like
public class Group
{
public class Generator
{
}
}
Group Group1=new Group()
Group Group2=new Group()
Group1.Generator Generator1=new Group1.Generator();
Group2.Generator Generator2=new Group2.Generator();
and have Generator1 and Generator2 be of different types?
For context, I am trying to write a group theory project where generators only make sense in their parent group, and I was hoping to avoid passing around explicit references to parent groups and checks to ensure parent objects are equal.
CodePudding user response:
You are confusing the ideas of instances and types. You can have different Types of Groups with either Generics or Subclasses, but it may not be necessary. Try first to see if you can model the domain with a single Group type and a single Generator type.
And using a Nested Type for Generator is not necessary in that design, eg simply use:
public class Generator
{
public Generator(Group group)
{
this.Group = group;
}
public Group Group { get; }
}
public class Group
{
public Generator Generator { get; }
public Group()
{
Generator generator = new Generator(this);
}
}
If Generator were Nested Type under Group, then it would have access to the private members of Group. But Nested Types don't get an automatic reference to an instance of the enclosing type, so you still have to pass a Group instance in its constructor.
CodePudding user response:
I am afraid that you can not use inner classes as you want because they are class-specific, not instance-specific.
If I understand you right, you want to have a mechanism to distinguish generators from the same group among others.
I may propose the following ways to achieve it:
- Encapsulate some group-specific values inside the Generator. You may implement the
Equals
method for Generator, which will compare those encapsulated values. If you do not want to pass those values explicitly, you can create a factory method inside Group, where you will create Generators related to this group and pass a group-specific value implicitly. - As @DavidG wrote, you may use generics. Each generic Group will be considered as a new class. So, in the following example
False
will be printed:
Group<int>.Generator Generator1 = new Group<int>.Generator();
Group<string>.Generator Generator2 = new Group<string>.Generator();
Console.WriteLine(Generator1.GetType() == Generator2.GetType());