I have a class Foo that has a field _customObject that must be initialized. I also have a class Bar that inherits from Foo:
public abstract class Foo
{
protected CustomObject _customObject;
public Foo()
{
// Do stuff
}
// Other methods that use _customObject
}
public class Bar : Foo
{
// Constructor and other methods
}
I can not initialize the object _customObject in Foo because every child inherited contains a different child of CustomObject, so it must be initialized in every child class:
public class Bar : Foo
{
public Bar()
{
_customObject = new CustomObjectInherited1();
}
}
public class Baz : Foo
{
public Baz()
{
_customObject = new CustomObjectInherited2();
}
}
Other people are going to implement new classes that inherit from Foo, so I was wondering if there is a way that an error in build time is shown, similar to when an abstract method is not implemented. If CustomObject is not initialized, a NullReferenceException will be thrown due to the use of the _customObject variable, ending in an application crash.
You can add a parameter to your Foo constructor:
public abstract class Foo
{
protected CustomObject _customObject;
public Foo(CustomObject obj)
{
// Do stuff
_customObject = obj;
}
// Other methods that use _customObject
}
Your derived classes will then be forced to call it, passing in a CustomObject, or something derived from it:
public class Bar : Foo
{
public Bar():base(new CustomObjectInherited1())
{
}
}
Not calling the base constructor will result in a compile time error. This doesn't entirely protect you, as someone could still pass null to the base constructor, but at least they'll have an explanation as to why they're getting a NullReferenceError at runtime.
You can force it by creating a abstract method which requires child classes to override it.
public abstract class Foo
{
protected abstract CustomObject CreateCustomObject();
}
public class Bar : Foo
{
protected override CustomObject CreateCustomObject()
{
return new BarCustomObject();
}
}
Or my favorite solution: Enforce it by generic constraints.
public abstract class Foo<T> : where T : CustomObject, new()
{
protected T _customObject;
public Foo()
{
this.CustomObject = new T();
}
}
public class Bar : Foo<BarCustomObject>
{
}
The answer provided by "James Thorpe" is correct (I've upvoted it already), but I wanted to share just another option here:
You could mark your class as abstract and introduce an abstract property instead of the "_customObject" field. That way, at least the first initializer will be forced to implement it. The downside is that you'll loose the enforcement on subsequent level subclasses:
public abstract class Foo
{
protected abstract CustomObject CustomObject {get; }
public Foo()
{
// Do stuff
}
// Other methods that use _customObject
}
public class Bar : Foo
{
// Constructor and other methods
protected override CustomObject CustomObject
{
get { return "X"; }
}
}
Also, with the first solution it's possible to validate the passed in value in the constructor - though, that'll be a runtime validation.
Related
abstract class Foo
{
private readonly FooAttributeCollection attributes;
public Foo(FooAttributeCollection attributes)
{
this.attributes = attributes;
}
}
class FooAttributeCollection
{
public FooAttributeCollection(Foo owner)
{
}
}
class Bar : Foo
{
public Bar() : base(new FooAttributeCollection(this))
{
}
}
Supposing that I have to write a code like above. and the classes Foo and FooAttributeCollection cannot be modified.
When I write Bar class like that, an error mentioned below:
'this' keyword cannot be used in this context.
occurs near the line base(...)
Is there any good idea to handle with this matter?
If Foo and FooAttributeCollection can't be modified, this code seems to be a bad design.
To instantiate a derivated Foo class you must instantiate FooAttributeCollection before and to instantiate FooAttributeCollection you must instantiate the same derivated Foo class.
Its a endless circular dependency impossible to resolve without 'cheating'
perhaps this problem can be resolve by refection (as say by Uwe Keim), or by using real proxy/dynamic proxy to create a proxy of DerivedClass.
Why don't affect attributes in abstract class ? If you want in FooAttributeCollection you can cast owner in Bar class.
abstract class Foo
{
private readonly FooAttributeCollection attributes;
public Foo(FooAttributeCollection attributes=null)
{
if(attributes = null) {attributes = new FooAttributeCollection(this);}
this.attributes = attributes;
}
}
class FooAttributeCollection
{
public FooAttributeCollection(Foo owner)
{
var ownerInBar = owner as Bar;
}
}
class Bar : Foo
{
public Bar() : base()
{
}
}
You can't write:
public Bar() : base(new FooAttributeCollection(this))
Because this, the current object, must be put in the implementation of a method, not in the method signature: here you have no access to the current instance of the object.
You can't do a such thing in every method declaration because you are out of the implementation scope, you are in the type def scope i.e. in the "interface" of the class, in its definition.
The use of calling base or side constructor with base or this keyword is a particular language construction to pass parameters that are not the instance of the class itself.
You can use the #Tohm solution to solve your goal.
the class needs to be constructed before you can access the this keyword.
You can try the bellow.
class Bar : Foo
{
private readonly FooAttributeCollection attributes;
public Bar() : base(null)
{
var attributes = new FooAttributeCollection(this);
}
}
Try this way:
public class Bar : Foo
{
public Bar(FooAttributeCollection attributes) : base(attributes)
{
}
}
Other Example:
public class BaseClass
{
int num;
public BaseClass(int i)
{
num = i;
Console.WriteLine("in BaseClass(int i)");
}
}
public class DerivedClass : BaseClass
{
// This constructor will call BaseClass.BaseClass(int i)
public DerivedClass(int i) : base(i)
{
}
}
Is there a neat way to specify that a class must contain a factory method that returns the same kind of object as the class that overrides the abstract method? (Edit: Or as Johnathon Sullinger more eloquently puts it, [...] have a base class enforce a child class to implement a method that returns an instance of the child class itself, and not allow returning an instance of any other Type that inherits from the base class.)
For example, if I've got two classes, SimpleFoo : BaseFoo and FancyFoo : BaseFoo, can I define an abstract factory method public TFoo WithSomeProp(SomeProp prop) where TFoo is a type parameter that is somehow fixed by the abstract method definition to the particular class that overrides it?
I had hopes of compile-time guarantees that either
a concrete WithSomeProp method definition in SomeFoo : BaseFoo will only be able to produce SomeFoos. If static abstract method definitions were legal, perhaps the following (pseudo-syntax) method extension best expresses this need:
public static abstract TFoo WithSomeProp<TFoo>(this TFoo source, SomeProp prop)
where TFoo : BaseFoo;
I don't think this is possible in C#.
or at least some way to parameterize the return type in an abstract method, e.g.
public abstract TFoo WithSomeProp<TFoo>(SomeProp prop)
where TFoo : BaseFoo;
This wouldn't prevent FancyFoo.WithSomeProp from returning SimpleFoos, but ok.
This abstract method itself seems to work, but my concrete definition then fails:
public override SimpleFoo WithSomeProp(SomeProp prop)
{
return new SimpleFoo(this.SomeOtherProp, ..., prop);
}
with the warning
no suitable method found to override
It appears to me that specifying type parameters in an abstract method does not allow fixing them in the overrides of those definitions, but rather it specifies that "A method with a type parameter should exist".
For now I simply have public abstract BaseFoo WithSomeProp(SomeProp prop);.
It sounds like what you want to do, is have a base class enforce a child class to implement a method that returns an instance of the child class itself, and not allow returning an instance of any other Type that inherits from the base class. Unfortunately, to the best of my knowledge, that is not something you can do.
You can however force the child-class to specify what it's Type is to the base class, so that the base class can then enforce that the return value must be the Type specified by the child-class.
For instance, given a base class called BaseFactory, and BaseFactory<T>, we can create an abstract class that requires children to specify to the parent, what type the creation method returns. We include a BaseFactory class so we can constrain T to only being children classes of BaseFactory.
EDIT
I'll leave the original answer below in the event that it helps, but after some thought, I think I've got a better solution for you.
You'll still need the base class to take a generic argument that defines what the child Type is. The difference now however is that the base class has a static creation method instead of instance methods. You can use this creation method to create a new instance of the child class, and optionally invoke a callback for configuring the property values on the new instance before you return it.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory, new()
{
public static TImpl Create(Action<TImpl> itemConfiguration = null)
{
var child = new TImpl();
itemConfiguration?.Invoke(child);
return child;
}
}
You then just create your children classes normally, without worrying about overriding any methods.
public class Foo : BaseFactory<Foo>
{
public bool IsCompleted { get; set; }
public int Percentage { get; set; }
public string Data { get; set; }
}
public class Bar : BaseFactory<Bar>
{
public string Username { get; set; }
}
Then you would use the factory as-such.
class Program
{
static void Main(string[] args)
{
// Both work
Bar bar1 = Bar.Create();
Foo foo1 = Foo.Create();
// Won't compile because of different Types.
Bar bar2 = Foo.Create();
// Allows for configuring the properties
Bar bar3 = Bar.Create(instanceBar => instanceBar.Username = "Jane Done");
Foo foo2 = Foo.Create(instanceFoo =>
{
instanceFoo.IsCompleted = true;
instanceFoo.Percentage = 100;
instanceFoo.Data = "My work here is done.";
});
}
Original Answer
The BaseFactory<T> will be reponsible for creating a new instance of TImpl and giving it back.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory
{
public abstract TImpl WithSomeProp();
}
Now, your child class can be created, and inherit from BaseFactory<T>, telling the base class that T represents itself. This means the child can only ever return itself.
public class Foo : BaseFactory<Foo>
{
public override Foo WithSomeProp()
{
return new Foo();
}
}
public class Bar : BaseFactory<Bar>
{
public override Bar WithSomeProp()
{
return new Bar();
}
}
Then you would use it like:
class Program
{
static void Main(string[] args)
{
var obj1 = new Bar();
// Works
Bar obj2 = obj1.WithSomeProp();
// Won't compile because obj1 returns Bar.
Foo obj3 = obj1.WithSomeProp();
}
}
If you really want to make sure that the generic specified is the same as the owning Type, you could instead make WithSomeProp a protected method, so that children classes can only see it. Then, you create a public method on the base class that can do type checking.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory
{
protected abstract TImpl WithSomeProp();
public TImpl Create()
{
Type myType = this.GetType();
if (typeof(TImpl) != myType)
{
throw new InvalidOperationException($"{myType.Name} can not create instances of itself because the generic argument it provided to the factory is of a different Type.");
}
return this.WithSomeProp();
}
}
public class Foo : BaseFactory<Foo>
{
protected override Foo WithSomeProp()
{
return new Foo();
}
}
public class Bar : BaseFactory<Bar>
{
protected override Bar WithSomeProp()
{
return new Bar();
}
}
class Program
{
static void Main(string[] args)
{
var obj1 = new Bar();
// Works
Bar obj2 = obj1.Create();
// Won't compile because obj1 returns Bar.
Foo obj3 = obj1.Create();
}
}
Now, if you create a child class that passes a different Type as T, the base class will catch it and throw an exception.
// Throws exception when BaseFactory.Create() is called, even though this compiles fine.
public class Bar : BaseFactory<Foo>
{
protected override Foo WithSomeProp()
{
return new Foo();
}
}
Not sure if this gets you what you wanted at least, but I think this will probably be the closest thing you can get.
Inspired by Johnathon Sullinger's fine answer, here is the code I ended with. (I added a theme.)
I passed the type parameter T along with the class definition and constrained that T : Base<T>.
BaseHyperLink.cs:
public abstract class BaseHyperLink<THyperLink> : Entity<int>
where THyperLink : BaseHyperLink<THyperLink>
{
protected BaseHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType)
: base(id)
{
this.HyperLink = hyperLink;
this.ContentType = contentType;
this.DocumentType = documentType;
}
public Uri HyperLink { get; }
public ContentType ContentType { get; }
public DocumentType DocumentType { get; }
public abstract THyperLink WithContentType(ContentType contentType);
}
SharedHyperLink.cs:
public sealed class SharedHyperLink : BaseHyperLink<SharedHyperLink>
{
public SharedHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType)
: base(id, hyperLink, contentType, documentType)
{
}
public override SharedHyperLink WithContentType(ContentType contentType)
{
return new SharedHyperLink(this.Id, contentType, this.DocumentType);
}
}
MarkedHyperLink.cs:
public sealed class MarkedHyperLink : BaseHyperLink<MarkedHyperLink>
{
public MarkedHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType, Mark mark)
: base(id, hyperLink, contentType, documentType)
{
this.Mark = mark;
}
public Mark Mark { get; }
public override MarkedHyperLink WithContentType(ContentType contentType)
{
return new MarkedHyperLink(this.Id, contentType, this.DocumentType, this.Mark);
}
}
Lets say I have a class such as this:
public abstract class Foo
{
public void Access(Foo foo)
{
/*
if (foo is same type as implemented)
AccessIfSameImplementation(foo);
else
AccessIfDifferentImplementation(foo);
*/
}
protected abstract void AccessIfSameImplementation(Foo foo);
private void AccessIfDifferentImplementation(Foo foo)
{
//do stuff with the different implementations
}
}
So the method Access takes a type of itself, by definition it will be an implementation in which we don't really care what it is as long as it inherits from Foo... But I want this method to check if the object passed in is the same type as its implementation.
Like so:
public class Bar : Foo
{
protected override void AccessIfSameImplementation(Foo foo)
{
// TODO: How do I force foo to always be a Bar
// do specific Bar stuff
}
}
Currently I have a Name field that indicates if the passed in foo.Name is the same as the current Name Besides that I thought about using generics but again don't think that's the right approach to this problem.
EDIT:
A little background on the actual structures I'm using.
The Foo class defined above is representative of a factory that creates a set of objects List<X> objs these objects are generated by the properties of the implemented Foo object. Now I have some other class comparing these factories but I don't wish for the factories to be, *bloated out by generating them all. So instead of *bloating the factories out I simply check if they have the same implementation, if so compare properties defined by the abstract comparer otherwise *blowout. I will add more later when I have some time.
If anyone has a better title please recommend one.
Aright so I guess I just can't think things entirely through. All that needs to be done is a type comparison directly in the public method Access
public void Access(Foo foo)
{
if (GetType() == foo.GetType) //Duh...
{
AccessIfSameImplementation(foo);
}
else
{
AccessIfDifferentImplementation(foo);
}
}
I'm not totally sure what your intention is, but you can't change the signature of an abstract method in the child class. One thought would be to do an argument check and throw an exception if you ever got an inappropriate foo:
public abstract class Foo
{
public void Access(Foo foo)
{
if (foo.GetType() == GetType())
{
AccessIfSameImplementation(foo);
}
else
{
AccessIfDifferentImplementation(foo);
}
}
protected abstract void AccessIfSameImplementation(Foo foo);
private void AccessIfDifferentImplementation(Foo foo)
{
//do stuff with the different implementations
}
}
public class Bar : Foo
{
public string Baz { get; set; }
protected override void AccessIfSameImplementation(Foo foo)
{
var bar = foo as Bar;
if (bar == null)
{
throw new ArgumentException("Argument foo is not of type Bar");
}
//Do Bar stuff below
bar.Baz = "Yay!";
}
}
Keep it simple. Keep your abstract class abstract, but give the Access method a default implementation that is Foo agnostic. Leave it up the a child class to provide custom implementation that uses members of that child class. You could also make it optional for the child class to fall back on the default logic implemented in the base class:
public abstract class Foo
{
public virtual void Access(Foo foo)
{
// perform the default implementation here, but mark as virtual to enable a child class to override it.
}
}
public class Bar : Foo
{
public override void Access(Foo foo)
{
var bar = foo as Bar;
if (bar != null)
{
// If you get here, that means foo is a Bar.
// Just use bar now and ignore foo.
}
else
{
// Fall back on the base classes implementation
base.Access(foo);
}
}
}
I have a base class like this:
class FooBase
{
public bool Do(int p) { /* Return stuff. */ }
}
And a child class like this:
class Foo<T> : FooBase
{
private Dictionary<T, int> Dictionary;
public bool Do(T p)
{
int param;
if (!Dictionary.TryGetValue(p, out param))
return false;
return base.Do(param);
}
}
If the user creates a Foo<string> object called "fooString", then he can call both fooString.Do(5) and fooString.Do("test") but if he creates a Foo<int> object called "fooInt", he can only call the Do method of the derived class. I prefer the second no matter what the T is.
The Do methods in both of these classes essentially do the same thing. The one in the derived class gets an integer from a Dictionary<T, int> using the given parameter and calls the Do method of the base class using it.
That's why I want to hide the Do method of the FooBase in Foo<T>. How can I achieve this or something similar? Any design advice to overcome this would also be nice.
but if he creates a Foo<int> object called "fooInt", he can only call the Do method of the derived class.
No, that's not true. If the declared type of the variable is FooBase, it will still call the FooBase method. You're not really preventing access to FooBase.Do - you're just hiding it.
FooBase foo = new Foo<int>();
foo.Do(5); // This will still call FooBase.Do
Full sample code to show that:
using System;
class FooBase
{
public bool Do(int p) { return false; }
}
class Foo<T> : FooBase
{
public bool Do(T p) { return true; }
}
class Test
{
static void Main()
{
FooBase foo1 = new Foo<int>();
Console.WriteLine(foo1.Do(10)); // False
Foo<int> foo2 = new Foo<int>();
Console.WriteLine(foo2.Do(10)); // True
}
}
That's why I want to hide the Do method of the FooBase in Foo.
You need to think about Liskov's Substitutability Principle.
Either Foo<T> shouldn't derive from FooBase (use composition instead of inheritance) or FooBase.Do shouldn't be visible (e.g. make it protected).
You could build a base class that is abstract with a protected Do method, and rewrite your current FooBase class to inherit from Foo<T>:
public abstract class FooBaseAbstract
{
protected bool Do(int p)
{
return true;
}
}
// You can use this one just as your current FooBase class
public class FooBase : Foo<int>
{
}
public class Foo<T> : FooBaseAbstract
{
public bool Do(T p)
{
if (true /* some test here */)
{
return base.Do(4);
}
return false;
}
}
(of course change the class names)
I need a method that creates an empty clone of an object in a base class? For instance:
public class ChildClass : ParentClass
{
public ChildClass()
{
}
}
public class ParentClass
{
public SomeMethod()
{
// I want to create an instance of the ChildClass here
}
}
Up until now, we have an abstract method defined in the parent class. And, all of the child classes implement them. But, the implementation is the same for all, just a different type.
public class ChildClass : ParentClass
{
public ChildClass()
{
}
public ParentClass CreateEmpty()
{
return new ChildClass();
}
}
public class ParentClass
{
public SomeMethod()
{
// I want to create an instance of the ChildClass here
ParentClass empty = CreateEmpty();
}
public abstract ParentClass CreateEmpty();
}
Is there any way to do this from the parent class so that I don't have to keep implementing the same logic for each different child class? Note that there may be more levels of inheritance (i.e. ChildChildClass : ChildClass : ParentClass).
If using reflection isn't a problem to you, you could do it using Activator class:
//In parent class
public ParentClass CreateEmpty()
{
return (ParentClass)Activator.CreateInstance(this.GetType());
}
This will return empty object of the type you want. Notice that this method does not need to be virtual.
On the other hand, I think that your current approach is perfectly fine, few more lines of code aren't so bad.
You can make a deep clone of the object using the binary serializer.
EDIT: Just noticed the word "empty" next to clone (which I thought was an oxymoron). Leaving this response up anyhow hoping it will help others that find this question because they are looking to do a regular clone.
This is somewhat experimental. I don't know whether this will lead to a cyclic dependency. Haven't touched C# for some months.
public class ParentClass<T> where T : ParentClass<T>, new() { // fixed
public ParentClass() {
var x = new T(); // fixed, was T.new()
}
}
public class ChildClass : ParentClass<ChildClass> {
public ChildClass() { }
}
Otherwise go for the ReflectionCode by Ravadre.
I'm using the following pattern.
Pros:
This pattern secure the type-safety of cloning in private and public sides of classes.
The output class will be always correct.
You never forgot override the "clone" method. The "MyDerivedClass" never returns another class than the "MyDerivedClass".
Cons:
For one class, you need create one interface and two classes (prototype and final)
Sample:
// Common interface for cloneable classes.
public interface IPrototype : ICloneable {
new IPrototype Clone();
}
// Generic interface for cloneable classes.
// The 'TFinal' is finaly class (type) which should be cloned.
public interface IPrototype<TFinal> where TFinal : IPrototype<TFinal> {
new TFinal Clone();
}
// Base class for cloneable classes.
// The 'TFinal' is finaly class (type) which should be cloned.
public abstract class PrototypeBase<TFinal> : IPrototype<TFinal> where TFinal : PrototypeBase<TFinal> {
public TFinal Clone() {
TFinal ret = this.CreateCloneInstance();
if ( null == ret ) {
throw new InvalidOperationException( "Clone instance was not created." );
}
this.FillCloneInstance( ret );
return ret;
}
// If overriden, creates new cloned instance
protected abstract TFinal CreateCloneInstance();
// If overriden, fill clone instance with correct values.
protected abstract void FillCloneInstance( TFinal clone );
IPrototype IPrototype.Clone() { return this.Clone(); }
object ICloneable.Clone() { return this.Clone(); }
}
// Common interface for standalone class.
public interface IMyStandaloneClass : IPrototype<IMyStandaloneClass> {
string SomeText{get;set;}
string SomeNumber{get;set;}
}
// The prototype class contains all functionality exception the clone instance creation.
public abstract class MyStandaloneClassPrototype<TFinal> : PrototypeBase<TFinal>, IMyStandaloneClass where TFinal : MyStandaloneClassPrototype<TFinal> {
public string SomeText {get; set;}
public int SomeNumber {get; set}
protected override FillCloneInstance( TFinal clone ) {
// Now fill clone with values
clone.SomeText = this.SomeText;
clone.SomeNumber = this.SomeNumber;
}
}
// The sealed clas contains only functionality for clone instance creation.
public sealed class MyStandaloneClass : MyStandaloneClassPrototype<MyStandaloneClass> {
protected override MyStandaloneClass CreateCloneInstance() {
return new MyStandaloneClass();
}
}
public interface IMyExtendedStandaloneClass : IMyStandaloneClass, IPrototype<IMyExtendedStandaloneClass> {
DateTime SomeTime {get; set;}
}
// The extended prototype of MyStandaloneClassPrototype<TFinal>.
public abstract class MyExtendedStandaloneClassPrototype<TFinal> : MyStandaloneClassPrototype<TFinal> where TFinal : MyExtendedStandaloneClassPrototype<TFinal> {
public DateTime SomeTime {get; set;}
protected override FillCloneInstance( TFinal clone ) {
// at first, fill the base class members
base.FillCloneInstance( clone );
// Now fill clone with values
clone.SomeTime = this.SomeTime;
}
}
public sealed class MyExtendedStandaloneClass : MyExtendedStandaloneClassPrototype<TFinal> {
protected override MyExtendedStandaloneClass CreateCloneInstance() {
return new MyExtendedStandaloneClass
}
}