How do I declare constructors for classes I inherit from? - c#

I have the following class:
public abstract class TableServiceEntity
{
protected TableServiceEntity();
protected TableServiceEntity(string partitionKey, string rowKey);
.....
.....
}
I inherit from this class as follows:
public class AuditableTableServiceEntity : TableServiceEntity
{
public string CreatedBy { get; set; }
.....
.....
}
I use the class as follows:
public class Note : AuditableTableServiceEntity
{
public Note() { }
public Note(string dsValue, string pk)
: base(pk, Seq.GetNext(dsValue, pk, "Note").ToString("00000")) { }
It fails saying that the class AuditableTableServiceEntity does not have a constructor that
takes two arguments. To fix I tried to add the following methods to AuditableTableServiceEntity. Is this a valid thing to do or is there some other way? Also I notice it requires me to add a constructor that takes zero arguments. Why is that?
public AuditableTableServiceEntity()
: base()
{
}
public AuditableTableServiceEntity(string pk, string rk)
: base(pk, rk)
{
}
Can someone give me advice as to if I'm on the right track or if there is some better way of doing this. Should I declare the methods on AuditableTableServiceEntity as protected and also should I declare that class as abstract?

Can someone give me advice as to if I'm on the right track or if there is some better way of doing this.
This is the correct approach.
Should I declare the methods on AuditableTableServiceEntity as protected and also should I declare that class as abstract?
It depends. Should the user be able to directly construct an instance of an AuditableTableServiceEntity? If so, then the constructors should be public, and the class should not be abstract.
If, however, it doesn't make sense, and the user should always construct a Note or other similar class, then protected constructors and an abstract class is appropriate.

Related

Empty interface or expose a private validation

I have a base abstract class that calls a private validation method in constructor. For part of its descendants I want to skip this check. This class have too many usages and I can't move the validation from the base class.
Which is better solution
create an empty interface, implemented in classes that will skip this check
expose this property and make it protected virtual and override it with empty body in derived classes that should skip the check
(any other better solutions will be also appreciated)
If this consideration applies only to this class, the 2nd approach I'd choose. If it will be the case in more classes, therefore it would represent some behaviour independent of class, I would go with 1st option (then also you can make use of polymorphism in cases, where you want to use just classes without check).
public abstract class BaseClass {
public BaseClass(bool? validate = true) {
if (validate.HasValue && validate.Value) {
Validate();
}
}
private void Validate() { }
}
public class ChildClass1 : BaseClass {
public ChildClass1() : base() { }
}
public class ChildClass2 : BaseClass {
public ChildClass2() : base(false) { }
}

Making Microsoft Unity dependency properties available in constructors

I've got the following bit of (simplified) code:
public abstract class BaseClass
{
[Dependency]
public IRequiredService RequiredService { get; set; }
protected string RequiredParameter { get; private set; }
public BaseClass(string requiredParameter)
{
this.RequiredParameter = requiredParameter;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(string requiredParameter) : base(requiredParameter)
{
RequiredService.DoSomething(); //this will fail!
}
}
In other words, I'd like to have access to the Unity-filled RequiredService in the constructor... but that's impossible, since that property hasn't been filled by Unity yet. I COULD add the IRequiredService as a required constructor parameter, but then I'd need to refactor every constructor of every derived class to also include that parameter.
I was wondering if there's a better way.
In short, I'd like to run a bit of code after a class has been constructed and after unity has filled all the class' properties marked with the [Dependency] attribute.
Is there a simple way to do this?
Instead of putting RequiredService.DoSomething(); in the constructor you can put it in a inside a [InjectionMethod] call, this will allow you to reliably know that RequiredService has been populated.

4 Classes with the same properties and methods - is it possible to create only one?

i have another question open here on SO and after thinking about it, i may be approaching this in the wrong way.
i have 4 classes, that have the same properties and methods.
some of the classes, have their own properties and methods ( not overrides of the existing ones ).
currently i create each class as:
public class ClassOne
{
public ClassOne()
{
}
public int ID {get;set;}
// More properties here
public void Set(){
// Do Stuff to save this
}
// More Methods here
}
cant i create one class that will generate all of the 4 classes?
and in the classes themselfs i only create specific properties/methods for that class?
repeating the code seems very odd to me, im sure there must be a way to do this, just dont know how.
Your situation is one of the main reasons why inheritance was invented. So with that, you can write
public class Base
{
// Properties and methods common to all
}
public class ClassOne : Base
{
// Properties and methods specific to ClassOne
}
public class ClassTwo : Base
{
// Properties and methods specific to ClassTwo
}
public class ClassThree : Base
{
// Properties and methods specific to ClassThree
}
public class ClassFour : Base
{
// Properties and methods specific to ClassFour
}
As requested, more code, using interfaces and abstract classes:
An interface is just a blueprint, defining what properties and methods are required to be compatible with other "BaseClasses"
public interface IBaseClass
{
public int ID {get;set;}
public void Set();
}
Abstract classes can contain code, but can not be instantiated, they are form of starting point for a class, but not a complete class themselves.
public abstract class ABaseClass : IBaseClass
{
public int ID {get;set;}
public void Set(){
// Do Stuff to save
}
}
Each class inherits from the abstract class and can then override and implement whatever it wants, customizing it however is necessary.
public class ClassOne : ABaseClass
{
}
public class ClassTwo : ABaseClass
{
}
public class ClassThree : ABaseClass
{
}
public class ClassFour : ABaseClass
{
}
ps. not entirely sure if my syntax is 100% correct
Could you simply make a base class with your properties and inherit from that class?
Why not use inheritance??
public class ClassOne
{
public ClassOne()
{
}
public virtual int ID {get;set;}
// More properties here
public virtual void Set(){
// Do Stuff to save this
}
// More Methods here }
public class ClassTwo : ClassOne
{
public string ClassTwoString { get; set; }
}
public class ClassThree : ClassOne
{
public string ClassThreeString { get; set; }
}
Can you make them all inherit off of the same class? If so, that sounds ideal.
Barring the possibility of making them inherit, you could write an interface that describes the methods and properties which each of them use. Then you can call each instance of the class through the same interface.
Barring again that possibility, you could write a reflective assignor/accessor. But you shouldn't do that.

What is the best way to design this class hierarchy?

I have a database table which contains an ID column and a Name column. I am tasked with designing a program that accepts one of the IDs as an argument to Main().
Bold is edit 2
I need to use that ID which must exist in the database, to correspond to some code to run. Each row in the table corresponds to slightly different code, but a lot of them share a lot of code. I need a design that will minimize code duplication.
So far what I've developed is an abstract base class that has an abstract Int32 field ID to enforce derived classes having their corresponding ID in the database. That way I can reflect over the derived classes to find the one whose ID matches the Main() argument and instantiate that class. Then I just call the virtual methods from Main() which runs the most derived code that has been defined.
public abstract class Base {
public abstract Int32 Id { get; }
public void Foo() {
// Do something
}
}
public class Derived {
public override Int32 Id { get { return 42; } }
public void Foo() {
// Do something more specific
}
}
Does anyone have any better ideas how to achieve what I want? I like the idea of keeping the ID right in the class definition, but I'm open to changing that if it makes sense.
Thanks!
EDIT:
One thing I don't like about this is that I have to reflect over each derived type and instantiate that type to check the ID. Does anyone have a better idea on how to do that?
Instead of using a property to define the ID of the class, use a custom attribute. That way, you don't have to instantiate the object to check what its ID is.
When your program runs, it can scan the assembly for all classes with that attribute tag, and find the one with the matching ID, instantiate that class, and then run it's Foo method. If you perform this kind of lookup multiple times per application run, you could instatiate all the classes with your custom attribute and then put them into a Dictionary to provide quick lookups by ID.
Your code might look something like this:
[AttributeUsage(AttributeTargets.Class)]
public class CommandAttribute {
public CommandAttribute(int id) {
ID = id;
}
public int ID { get; private set; }
}
public abstract class Command {
public abstract void Execute();
}
[Command(2)]
public class MyCommand : Command {
public override void Execute() {
//Do something useful
}
}
The other advantage of using a custom attribute is that you have to explicitly tag everything that is a candidate for being instantiated and executed by ID, rather than assuming than anything derived from your base class is a candidate. If you are sharing code between the classes, you might want to make a common base class for them that derives from your base class, but should not be instantiated or executed on its own.
One thing I don't understand is, what is the point of the "Name" field if the class you want to run is identified by the ID? If you can decide what the name of each ID is, then you could use the name field as the fully qualified type name of the class you want to execute, which then avoid having to scan through all the types in your assembly (or application domain, depending upon the scope of your search). That setup is a bit more prone to typos, however.
It sounds like you need to implement a factory pattern.
I would define an interface:
public interface IWidget
{
void Foo();
}
Then the base class:
public abstract class WidgetBase : IWidget
{
public void Foo()
{
this.Bar()
}
protected virtual void Bar()
{
// Base implementation
}
}
The factory:
public static WidgetFactory
{
public static IWidget Create(int id)
{
// Get class name from id, probably use the name in your database.
// Get Type from class name
// Get constructor for Type
// Create instance using constructor and return it.
}
}
A derived class:
public class DerivedWidget : WidgetBase
{
protected override void Bar()
{
// call base implementation
base.Bar();
// derived implementation
}
}
In your main:
public void Main(int id)
{
var widget = WidgetBase.Create(id);
widget.Foo();
}
I like #Xint0's idea of using a Factory for this kind of task, but I thought I'd still contribute another answer.
A better way to implement your original design would be to pass the ID to the base constructor as follows:
public abstract class Base {
public Int32 Id { get; private set; }
protected Base(Int32 id) {
this.Id = id;
}
public void Foo() {
// Do something
}
}
public class Derived : Base {
public Derived : base(42) {}
public void Foo() {
// Do something more specific
}
}

How can I prevent a base constructor from being called by an inheritor in C#?

I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
public BaseClass(int someValue) {}
//...more code, not important here
}
and, my proxy resembles:
public BaseClassProxy : BaseClass
{
public BaseClassProxy(bool fakeOut){}
}
Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.
There is a way to create an object without calling any instance constructors.
Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.
This is how you do it:
FormatterServices.GetUninitializedObject(typeof(MyClass));
Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.
When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.
If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.
At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.
I don't believe you can get around calling the constructor. But you could do something like this:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
protected virtual void Setup()
{
}
}
public BaseClassProxy : BaseClass
{
bool _fakeOut;
protected BaseClassProxy(bool fakeOut)
{
_fakeOut = fakeOut;
Setup();
}
public override void Setup()
{
if(_fakeOut)
{
base.Setup();
}
//Your other constructor code
}
}
If what you want is to not call either of the two base class constructors, this cannot be done.
C# class constructors must call base class constructors. If you don't call one explicitly, base( ) is implied. In your example, if you do not specify which base class constructor to call, it is the same as:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base() { }
}
If you prefer to use the other base class constructor, you can use:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base(someIntValue) { }
}
Either way, one of the two will be called, explicitly or implicitly.
When you create a BaseClassProxy object it NEEDS to create a instance of it's base class, so you need to call the base class constructor, what you can doo is choose wich one to call, like:
public BaseClassProxy (bool fakeOut) : base (10) {}
To call the second constructor instead of the first one
I am affraid that not base calling constructor isn't option.
I ended up doing something like this:
public class BaseClassProxy : BaseClass
{
public BaseClass BaseClass { get; private set; }
public virtual int MethodINeedToOverride(){}
public virtual string PropertyINeedToOverride() { get; protected set; }
}
This got me around some of the bad practices of the base class.
constructors are public by nature. do not use a constructor and use another for construction and make it private.so you would create an instance with no paramtersand call that function for constructing your object instance.
All right, here is an ugly solution to the problem of one class inheriting the constructors of another class that I didn't want to allow some of them to work. I was hoping to avoid using this in my class but here it is:
Here is my class constructor:
public MyClass();
{
throw new Exception("Error: Must call constructor with parameters.");
}
OK now you were warned that it was ugly. No complaints please!
I wanted to force at least the minimal parameters from my main constructor without it allowing the inherited base constructor with no parameters.
I also believe that if you create a constructor and do not put the : base() after it that it will not call the base class constructor. And if you create constructors for all of the ones in the base class and provide the same exact parameters for them in the main class, that it will not pass through. But this can be tedious if you have a lot of constructors in the base class!
It is possible to create an object without calling the parameterless constructor (see answer above). But I use code like this to create a base class and an inherited class, in which I can choose whether to execute the base class's init.
public class MyClass_Base
{
public MyClass_Base()
{
/// Don't call the InitClass() when the object is inherited
/// !!! CAUTION: The inherited constructor must call InitClass() itself when init is needed !!!
if (this.GetType().IsSubclassOf(typeof(MyClass_Base)) == false)
{
this.InitClass();
}
}
protected void InitClass()
{
// The init stuff
}
}
public class MyClass : MyClass_Base
{
public MyClass(bool callBaseClassInit)
{
if(callBaseClassInit == true)
base.InitClass();
}
}
Here is my solution to the problem
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(new Child().Test);
}
public class Child : Parent {
public Child() : base(false) {
//No Parent Constructor called
}
}
public class Parent {
public int Test {get;set;}
public Parent()
{
Test = 5;
}
public Parent(bool NoBase){
//Don't do anything
}
}
}
A simple elegant solution. You can change it according to your need.
Another simple solution from me:
class parent
{
public parent()
{
//code for all children
if (this.GetType() == typeof(child1))
{
//code only for objects of class "child1"
}
else
{
//code for objects of other child classes
}
}
}
class child1 : parent
{
public child1()
{}
}
// class child2: parent ... child3 : parent ... e.t.c

Categories

Resources